For loop with if and elseif statements

조회 수: 2 (최근 30일)
Santos García Rosado
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

채택된 답변

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
Santos García Rosado
Santos García Rosado 2021년 3월 22일
That solved it! Thank's for your time Matt!

댓글을 달려면 로그인하십시오.

추가 답변 (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