For loop with if and elseif statements

2 Ansichten (letzte 30 Tage)
Santos García Rosado
Santos García Rosado am 22 Mär. 2021
Could someone please help me out?
I've been writting a code for some time now, and I endend up having quite a big matrix for loop with many statements. Now I want to modify that loop and some of it's statements, but I came up with some issues. First of all, I'd like to know if I coud write a new statement where I could ask the program to skip some iterations within the loop until a certain position on my matrix. For example, let's say I have an Input A(m,n) such as:
A = [2 0.5 1 2 0 -1 0 -1 6 4 3 0 ; 0 3 4 0.5 6 0 0 -1 0 0 -1 0];
What I expect from the code is to add the value of each position to the addition of the previous ones, except when the value is 0.5, that I'd like to hold the value until you come up with a -1, where I'd like to multiplyit by 2.
Expected Output:
Out = [2 2 2 2 2 4 4 8 14 18 21 21; 0 3 7 7 7 7 7 14 14 14 24 24]
Any help with this? Also, would it be interesting changing this part of the code from is and elseif statements to a switch case structure?
Thank's for the help,
Santos

Akzeptierte Antwort

Matt J
Matt J am 22 Mär. 2021
  7 Kommentare
Matt J
Matt J am 22 Mär. 2021
AAA = [0 0.5 1 2 0 -1 0 -1 6 4 3 0 ; 0 3 4 0.5 6 0 0 -1 0 0 -1 0];
BBB = zeros(size(AAA));
% BBB(1,:) = AAA(1,:);
for f = 1:size(AAA,1)
holdState=0;
for c = 2:size(AAA,2)
if AAA(f,c) == 0.5 || (holdState && AAA(f,c)~=-1)
BBB(f,c) = BBB(f,c-1);
if AAA(f,c) == 0.5, holdState=1; end
elseif AAA(f,c) == -1
BBB(f,c) = BBB(f,c-1) * 2;
holdState=0;
else
BBB(f,c) = BBB(f,c-1) + AAA(f,c);
end
end
end
BBB
BBB = 2×12
0 0 0 0 0 0 0 0 6 10 13 13 0 3 7 7 7 7 7 14 14 14 28 28
Santos García Rosado
Santos García Rosado am 22 Mär. 2021
That solved it! Thank's for your time Matt!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by