Softlogic Systems - Placement and Training Institute in Chennai

Easy way to IT Job

Matlab Programming Challenges and Code Solutions for Beginners
Share on your Social Media

Most Popular Matlab Programming Challenges and Code Solutions for Beginners

Published On: November 26, 2024

Matlab is an effective tool for various fields, such as computing, engineering, and mathematics. This article provides beginners with insight into Matlab challenges and solutions so they may utilize the program more effectively. Explore what our Matlab course syllabus has in store. 

Matlab Problems and Solutions for Beginners

The following are some MATLAB problems that beginners could run into and their fixes: 

Challenges with Memory Leaks in Matlab

Challenge: Memory leaks may arise from improper implementation of data structures, code optimization, and memory management. As a result, system resource use may rise without program performance increasing in tandem. 

Solutions: Users can stop memory leaks by:

  • Recognize how MATLAB uses memory.
  • Technologies such as memory profiling and debugging should be used to guarantee effective resource management.
  • Develop sound coding practices by designing data structures correctly and optimizing your code.  

Challenges with Errors and Warnings in Matlab

Users can utilize MATLAB to look for errors and warnings by:

  • Right-click on the code that is highlighted.
  • From the context menu, pick the recommended solution.
  • If a problem occurs more than once, MATLAB can apply the recommended solution to each occasion.

Learn the basics through the Matlab tutorial for beginners

Matlab Exercises and Solutions

Here you can find various Matlab code challenges and solutions useful for beginners and professionals. Get a free Matlab exercises and solutions PDF from our trainers and train your brain for a bright career. 

Create a Checkerboard Matrix in Matlab

Challenge: The rectangular checkerboard picture produced by I = checkerboard(n, p, q) has p as the number of tile rows and q as the number of tile columns. The checkerboard is square and the number of columns defaults to p if q is left out. 

Code Solution:

function a = checkerboard(n)

    a = ones(n);    

    for j = 1:2:n

        for i = 2:2:n

            a(i,j) = 0;

        end

    end

    for j = 2:2:n

        for i = 1:2:n

            a(i,j) = 0;

        end

    end

end

Determine Whether a Vector is Monotonically Increasing

Challenge: If the input vector’s items grow monotonically, that is, if each element gets bigger than the one before it, then return true. Otherwise, return false.

Example: 

Input x = [-3 0 7]

Output tf is true

Input x = [2 2]

Output tf is false

Code Solution:

function tf = mono_increase(x)

    if length(x) > 1

        for i = 2:length(x)

            if x(i) <= x(i-1)

                tf = false;

                break

            else

                tf = true;

            end

        end

    else

        tf = true;

    end

end

Generate Fibonacci Sequence in Matlab

Challenge: Determine the Fibonacci number n.

Where f = fib(n) and f(1) = 1, f(2) = 1, f(3) = 2,…, return f given n.

Example:

 Input  n = 5

 Output f is 5

 Input  n = 7

 Output f is 13

Code Solution:

function f = fib(n)  

  sequence = zeros(1,n);

  sequence(1,1) = 1;

  sequence(1,2) = 1;

  if n == 1

      f = 1;

  elseif n == 2

      f = 1;

  else 

      for i = 3:n

          sequence(1,i) = sequence(1,i-1) + sequence(1,i-2);

      end

      f = sequence(1,n);

  end

end

Create TimeTables in Matlab

All of us have had to commit tedious times tables to memory at some point. Five times five equals twenty-five. 30 equals 5 times 6. Twelve times twelve is much more than you might imagine. 

Challenge: Making times tables should be simple with MATLAB! Create a function that generates times tables of the specified size.

Example:

Code Solution:

function m = timestables(n)

  m = zeros(n);

  counter = 1;  

  for i = 1:n

      m(1,i) = counter;

      m(i,1) = counter;

      counter = counter + 1;

  end

  for i = 2:n

      for j = 2:n

          m(i,j) = m(i,1)*m(1,j);

      end

  end

  end

Solve equations in Matlab with our Matlab project ideas

Finding the Mean of Prime Numbers in Matlab

Challenge: The matrix will always contain at least one prime. Find the mean of prime numbers. 

Example:

 Input  in = [ 8 3

               5 9 ]

 Output out is 4 or (3+5)/2

Code Solution:

function out = meanOfPrimes(in)

    primeTF = isprime(in);

    primeTFIndex = find(primeTF);

    x = [];

    for i = 1:length(primeTFIndex)

        x = [x, in(primeTFIndex(i))];

    end    

    out = mean(x);

end

Pascal’s Triangle in Matlab

Challenge: Create the length n+1 row vector that represents the n-th row of Pascal’s Triangle given an integer n >= 0. 

Example:

 pascalTri(0)

 ans =

     1

 pascalTri(1)

 ans =

     1     1

 pascalTri(2)

 ans =

     1     2     1

Code Solution:

function y = pascalTri(n)    

    if n == 0

        y = [1];

    elseif n == 1

        y = [1 1];

    elseif n == 2

        y = [1 2 1];

    else

        numele = n + 1;

        previous = pascalTri(n-1);

        y = zeros(1,numele);

        y(1) = 1;

        y(end) = 1;

        for i = 2:numele-1

            y(i) = previous(i)+previous(i-1);

        end    

end    

end

Find the Longest Sequence of 1’s in a Binary Sequence in Matlab

Challenge: Given a string like 

 s = ‘011110010000000100010111’

determines the length of the longest sequence of consecutive ones. The response in this case would be 4.

Example:

 Input  x = ‘110100111’

 Output y is 3

Code Solution:

function maxCount = lengthOnes(x)

    %% convertsion into numerical array

    a = 1234;

    b = num2str(x)-‘0’;

    %% initializing

    count = 0;

    maxCount = 0;

    if b(1) == 1

        count = 1;

        maxCount = 1;

    end

    %% main

    for i = 2:length(b)

        if b(i) == 1

            if b(i) == b(i-1)

                seq_repeat = true;

            else

                seq_repeat = false;

            end

            if seq_repeat == true

                count = count + 1;

            else

                count = 1;

            end

            if count > maxCount

                maxCount = count;

            end

        else

            count = 0;

        end

    end

end

Target Setting in Matlab

Challenge: Sort the provided list of numbers by the distance between each entry and the desired value t. The outcome ought to yield a list of the absolute values of the difference between a(n) and t, arranged in descending order.

Thus, the output b should be [1 2 4 17 8] if a = [1 2 4 8 17] and t = 12. 

Code Solution:

function a_sorted = targetSort(a,t)

    dist_vector = [];

    for i = 1:length(a)

        dist_vector = [dist_vector, norm(a(i)-t)];

    end

    dist_pair = zeros(length(a),2);

    dist_pair(:,1) = dist_vector’;

    dist_pair(:,2) = a’;

    dist_pair_sorted = sortrows(dist_pair,’descend’);    

    a_sorted = dist_pair_sorted(:,2)’;

end

Finding the Alphabetic Word Product in Matlab

Challenge: The output word product p is a number based on the correspondence a=1, b=2,… z=26 if the input string s is a word like “hello.” Despite the possibility of a mixed case, assume the input will consist of a single word. Keep in mind that B=b=2 and A=a=1.

Thus,  s = ‘hello’ means

 p = 8 * 5 * 12 * 12 * 15 = 86400

Code Solution:

function product = word_product(string)    

    small_alphabet = char(97:122);

    large_alphabet = char(65:90);

    product = 1;

    alphabet_value = strings(length(small_alphabet),2);    

    for i = 1:length(small_alphabet)

        alphabet_value{i,1} = small_alphabet(i);

        alphabet_value{i,2} = large_alphabet(i);

    end

    for k = 1:length(string)

        [order,~] = find(strcmp(alphabet_value, string(k)));

        product = product*order;

    end        

end

Fine-tune your skills with our Matlab interview questions and answers

Pangrams in Matlab

Challenge: A sentence that uses every letter of the alphabet at least once is called a pangram, or holoalphabetic sentence.

Example:

Input  s = ‘The quick brown fox jumps over the lazy dogs’

Output tf = true

Code Solution:

function tf = isPangram(s)    

    letters_small = ‘abcdefghijklmnopqrstuvwxyz’;

    letters_capital = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’;

    %% Find indexes where string characters are members of alphabet

    [~,index_small] = ismember(s,letters_small);

    [~,index_capital] = ismember(s,letters_capital);

    %% Combine to find total unique sorted indexes

    index = [index_small index_capital];

    index_unique = unique(index);

    %% Remove zeros (unnecessary)

    index_unique(index_unique == 0) = [];

    %% Check to pangram condition

    array_check = 1:26;

    tf = isequal(index_unique,array_check)    

end

Replace NaN’s with Numbers using Matlab

The number that appears to the left of NaNs in the row should be substituted.

Challenge: The first non-NaN value immediately to the left of the leftmost NaN shall take the place of any subsequent NaNs if there is more than one. Set the default value to zero if the NaN is in the first column.

Example:

x = [NaN  1   2  NaN NaN 17  3  -4 NaN]

then

y = [ 0   1   2   2   2  17  3  -4  -4]

Code Solution:

function out = replace_nans(in)    

    out = in;

    %% Starting from the end & approach to the start

    for i = length(out):-1:1

        if isnan(out(i)) == 1

            out(i) = checkPrevious(out,i);

        else

            continue;

        end

    end    

    %% Recursion function

    function out_value = checkPrevious(A,k)

        if k == 1

            out_value = 0;

        else

            if isnan(A(k-1)) == 1        

                out_value = checkPrevious(A,k-1);

            else

                out_value = A(k-1);

            end    

        end

    end

end

Palindrome Number in Matlab

For example, 323 is a palindrome. Some numbers, such as 124, aren’t. However, notice what occurs when we add that number to a copy of itself that has been inverted.

Challenge: Create a Palindrome program in Matlab

Code Solution:

function new_a = find_palindrome(a)

    a_str = num2str(a);

    status_palindrome = check_palindrome(a_str);

    %% Recursion to find palindrome integer

    if status_palindrome == false

        new_a = str2num(a_str) + str2num(flip(a_str));

        new_a = find_palindrome(new_a);

    else

        new_a = a;

    end

    %% Function to check palindrome: symmetry of string

    function palindrom_status = check_palindrome(str_num)

        for i = 1:length(str_num)/2

            if strcmp(str_num(i),str_num(end+1-i)) == 1

                palindrom_status = true;

            else

                palindrom_status = false;

            end

        end

    end

end

Knight’s Tour Checker in Matlab

Challenge: Find out if there is a lawful knight’s tour in a given matrix. The knight’s tour does not have to fill the entire matrix, but it always follows the pattern 1, 2, 3,… Zeros are present in any unused squares.

If a knight’s trip is represented by the counting sequence from 1 to n, your function should return true; otherwise, it should return false.

Example:

The following matrix is a knight’s tour of the law. Despite being inaccessible, the middle square satisfies the criteria because it contains a zero. TRUE should be the function’s return value. 

This is another knight’s legitimate tour, albeit brief. There will always be at least one move (i.e., the counting sequence [1 2]) in the test suite. Keep in mind that a square matrix is not necessary.

This is an unauthorized knight’s tour. Up until the jump from row 14 to row 15, which is unlawful because it goes from row 4 to row 1, everything is OK.

Code Solution:

function tf = knights_tour(a)

    %% Find all nonzero elements and their number

    [r,c,ind] = find(a);

    num_elems = numel(find(a));

    %% Make an array of: index, row and col

    cells = zeros(num_elems,3);

    cells(:,1) = ind;

    cells(:,2) = r;

    cells(:,3) = c;    

    %% Sort according to ind

    cells_sorted = sortrows(cells);

    %% Set default state

    tf = true;    

    for i = 1:size(cells_sorted,1)-1

        %% Knight move is ‘L’shaped as defined here

if (abs(cells_sorted(i+1,2)-cells_sorted(i,2)) == 1) && (abs(cells_sorted(i+1,3)-cells_sorted(i,3)) == 2) … 

|| (abs(cells_sorted(i+1,2)-cells_sorted(i,2)) == 2) && (abs(cells_sorted(i+1,3)-cells_sorted(i,3)) == 1)

            %% Skip correct knight moves

        else

            %% Set state to false once incorrect knight move occurs

            tf = false;

        end

    end    

end

Choose your desired career with our wide range of software training courses

Conclusion

We hope this article will be useful to you for the practical challenges of Matlab. Make use of these solutions and get expertise. If you are completely new, join SLA for the best Matlab training in Chennai

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.