How to stop loop from giving my matrix a certain value?

4 views (last 30 days)
I have a zeros matrix
Matrix= zeros(3,1);
and another matrix ;Main
Main= [10 20;25 -30;35 40];
I also have an if-elseif condition.
for c=1:size(Main, 1)
if Main(c,1)<0 || Main(c,2)<0
a= ['this is negative'];
disp(a);
elseif Main(c,1)>0 && Main(c,2)>0
Matrix=Func(test,quiz);
end
end
disp(Matrix);
Basically, function Func adds the test and quiz together, and the Main matrix first column is test, second column is quiz.
It only runs the elseif and calls Func if all the values in the Main is positive and store the output in the corresponding Matrix. In this case, the second row has a negative, therefore it should display "this is negative" and the value of Matrix should be zero for that location.
if I do
disp(Matrix);
What I want to display is
30
0
75
however, it calculates the second row anyway and comes out with
30
-5
75
also I think the reason why it runs anyway is that I put in the command window the values of test and quiz, therefore it ran the 25 and -30 anyway. how do i stop this?
how do keep corresponding Matrix to remain zero if the inouts are negative?
Thanks!

Answers (1)

Bob Thompson
Bob Thompson on 26 Nov 2018
I suspect the issue is that you are not indexing Matrix during your elseif condition. If you want to run the loop you should set up Func to solve for one row at a time, rather than the entire matrix.

Categories

Find more on Performance and Memory 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!