For loop with if and elseif statements
1 回表示 (過去 30 日間)
古いコメントを表示
Santos García Rosado
2021 年 3 月 22 日
コメント済み: Santos García Rosado
2021 年 3 月 22 日
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
0 件のコメント
採用された回答
Matt J
2021 年 3 月 22 日
7 件のコメント
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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!