Reputation: 1
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
andB
. 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 formulaA(i,j) = a*i +b*j
; wherea
andb
are the last two digits of your matric ID (herea = 2
andb = 5
).i
andj
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 matrixA
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
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