how to write if statement for matrix ?

37 Ansichten (letzte 30 Tage)
Ibrahim AlZoubi
Ibrahim AlZoubi am 16 Mai 2020
Kommentiert: Geoff Hayes am 18 Mai 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)

Antworten (1)

Geoff Hayes
Geoff Hayes am 16 Mai 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 Kommentare
Ibrahim AlZoubi
Ibrahim AlZoubi am 17 Mai 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 am 18 Mai 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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by