how to write if statement for matrix ?

38 views (last 30 days)
Ibrahim AlZoubi
Ibrahim AlZoubi on 16 May 2020
Commented: Geoff Hayes on 18 May 2020
how to write if statement for matrix ?
in other words:
test= [5;6;0;-1;0]
this is the condition:
if test==0
disp 0
else
disp 5
end
and I want to give answer for each row (for 5 and 6 and 0 ....etc)

Answers (1)

Geoff Hayes
Geoff Hayes on 16 May 2020
Ibrahim - what are you trying to do here? Just display (with disp) a message depending upon whether an element is a zero or not? The simplest and least efficient way to do this is with a loop
test = [5;6;0;-1;0];
for k = length(test)
if test(k) == 0
disp 0;
else
disp 5;
end
end
I don't think that is what you really want though so you may need to provide more details. I also suspect that you shouldn't need to use a for loop and that may be the case depending upon the details you provide.
  2 Comments
Ibrahim AlZoubi
Ibrahim AlZoubi on 17 May 2020
I have two matrices first one is:
test = [5;6;0;-1;0;5;0;6;0;8];
and the second one is:
test5 = [2;6;8;-1;0;7;8;6;8;8];
how to generate third matrix which is the result after the condition (if statment)...
the condition is if the value of test is equal 0 then the value of the new matrix is 0 , else if the value of the first matrix isn't equal 0 do some calculations on the second matrix which is test5 like (test5*7+5).
so the third matrix values depends on the two matrix before...
Geoff Hayes
Geoff Hayes on 18 May 2020
Is the output array of the same dimensions as test?
test = [5;6;0;-1;0];
outputArray = size(test);
for k = length(test)
if test(k) == 0
outputArray(k) = 0;
else
% do a calculation of some kind
outputArray(k) = 42; % <--- your code here
end
end

Sign in to comment.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!