Question:
How to create Matrix using for loop and if-else statement in MATLAB?
Answer:
Let's create a square matrix of size \(5 \times 5\) in MATLAB with diagonal element a scalar (say 3) and all other elements (say -1).
Here is the MATLAB script:
m = 5;
n = 5;
% A is matrix of m rows and n columns
A = zeros(m,n);
for i = 1:m
for j = 1:n
if i == j
A(i,j) = 3;
else
A(i,j) = -1;
end
end
end
disp(A)
disp('We are Done!!!')
OUTPUT
A =
3 -1 -1 -1 -1
-1 3 -1 -1 -1
-1 -1 3 -1 -1
-1 -1 -1 3 -1
-1 -1 -1 -1 3
We are Done!!!

1 Comments
Perfect 👌
ReplyDelete