Problems with a if statement in a for-loop
9 views (last 30 days)
Show older comments
Hi,
My plan for the code is following:
- read all rows from 1 to anzahl_runs (=number of rows)
- If there is a 1 in the row -> Divide two double vectors through each other, if there is no 1, delete the row
- Save this ratios in a new vector.
I tried it this way:
for k=1:anzahl_runs
if any (intens_RL(k,:)==1)
Ratio(k,1)=SpalteSr87(k,:)/SpalteSr86(k,:);
else
intens_RL(k,:)=[];
end
end
Ratio should be a new created vector.
But at the moment the line Ratio.... gives me following error:
Index in position 1 exceeds array bounds (must not exceed 181).
Error in TOF_Skript_SingleParticlesSrNdOs (line 96)
if any (intens_RL(k,:)==1)
I appreciate any help :-)
2 Comments
Accepted Answer
KSSV
on 21 Apr 2022
Edited: KSSV
on 21 Apr 2022
id = true(anzahl_runs,1) ;
for k=1:anzahl_runs
if any (intens_RL(k,:)==1)
Ratio(k,1)=SpalteSr87(k,:)/SpalteSr86(k,:);
id(k) = 0 ;
end
end
intens_RL(id,:)=[];
I suspect, as you are removing the rows in else condition, the number of rows in intens_RL will reduce, if the condition is not met. So this error popped out. Get the indices where the condition is not met and after the loop, you remove these rows from the array. You may try the above code.
5 Comments
KSSV
on 21 Apr 2022
nnz((intens_RL(k,:) > 1))
The above gives how many values are greater than 1.
More Answers (1)
Dyuman Joshi
on 21 Apr 2022
Edited: Dyuman Joshi
on 21 Apr 2022
So, Anzahl_runs is 260 meaning the for loop will run from 1 to 260.
Suppose your condition did not find a 1 in any row, so it will delete that row from the matrix. Now your matrix doesn't have 260 rows. So when the loop variable reaches a value greater than the number of rows your matrix has, this error shows up.
So, If x number of rows do not have 1 at all, your matrix will be reduced to 260-x rows. As soon as k reaches 260-x+1 (181 in your case), this error will be displayed and your code will stop running.
You can use a while loop or get the index of the rows from for loop and delete them after the loop
See Also
Categories
Find more on Loops and Conditional Statements 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!