How to check if an element of matrices is even or not in MATLAB?

I have a problem as follows -

Script: Using ’If’ condition inside a ’for’ loop

  • Create a new script and save it using your name and matric ID.
  • Use ’for’ loop to create two matrices A and B. The size of the matrices are same, and the matrices are of 5 by 4 size.
  • Each element of the matrix A will be determined in the ’for’ loop using the following formula A(i,j) = a*i +b*j; where a and b are the last two digits of your matric ID (here a = 2 and b = 5). i and j are the row number and column number of the matrices respectively.
  • The elements of the matrix B will be changed from 0 to 1 ’if’ the corresponding element of the matrix A is even number.

I tried to solve in this way but it won't work. What is the correct way to check if an element is even or not in MATLAB matrices?

clc
% clear all
A = zeros(5,4);
B =  zeros(5,4);
for j = 1:5
    for i = 1:4
        A(i,j) = 2*i + 5 * j;
        if mod(B(i,j),2) == 0
            A(i,j) = 1;
        end
    end
end

Upvotes: 0

Views: 191

Answers (1)

Patrick Happel
Patrick Happel

Reputation: 1351

These lines in your code

        if mod(B(i,j),2) == 0
            A(i,j) = 1;
        end

set A(i,j) to 1 if mod(B(i,j)) == 0. This is always true since you have initialized B with zeros. You shloud do it the other way around, test if mod(A(i,j),2) == 0 and set B(i,j) = 1

Upvotes: 1

Related Questions