For loop with if and elseif statements

1 次查看(过去 30 天)
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

采纳的回答

Matt J
Matt J 2021-3-22
  7 个评论
Matt J
Matt J 2021-3-22
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by