필터 지우기
필터 지우기

Problems with a if statement in a for-loop

조회 수: 1 (최근 30일)
Tatjana Mü
Tatjana Mü 2022년 4월 21일
댓글: KSSV 2022년 4월 21일
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
Chunru
Chunru 2022년 4월 21일
What are sizes of SpalteSr87 and SpalteSr86?
Tatjana Mü
Tatjana Mü 2022년 4월 21일
Both are 260x1 double
Anzahl_runs is 260 because the file I read in is 260 rows to 303 columns.

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

채택된 답변

KSSV
KSSV 2022년 4월 21일
편집: KSSV 2022년 4월 21일
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
Tatjana Mü
Tatjana Mü 2022년 4월 21일
But then I would say, select this row if there is a value over 1, isn't it? But I want to say: If there are two or more 1 in a row, do this calculations.
KSSV
KSSV 2022년 4월 21일
nnz((intens_RL(k,:) > 1))
The above gives how many values are greater than 1.

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

추가 답변 (1개)

Dyuman Joshi
Dyuman Joshi 2022년 4월 21일
편집: Dyuman Joshi 2022년 4월 21일
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
  댓글 수: 1
Tatjana Mü
Tatjana Mü 2022년 4월 21일
Thank you for this explanation. You are right, I didnt think about this point. Thank you a lot!

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by