How to call a function inside a loop with a counter?

조회 수: 1 (최근 30일)
Ann G
Ann G 2016년 3월 30일
댓글: Ann G 2016년 3월 30일
I want to call a function inside a loop..I call it like that:
flag=0;
for i=1:3
flag=flag+1;
mean(flag)=mean_value(I);
end
But it is not right..What should I do?

채택된 답변

Image Analyst
Image Analyst 2016년 3월 30일
편집: Image Analyst 2016년 3월 30일
I don't know what the function mean_value() does, but it's not getting anything different from one iteration to the next because the badly-named I is not changing inside the loop, so the very same I is going to the mean_value() function on each iteration. This does not make sense.
The other big, big problem is that your mean_value() function may well use the mean() function inside it. However, you overwrite the mean() function by assigning the result of mean_value() to it. Now perhaps the mean() function inside mean_value will still work, but maybe it won't. Either way, it's a horrible, bad, and unwise decision to name a variable/array after the name of a built-in function. Call it "theMeans" or something else, but certainly not "mean".
Also, flag is unnecessary. You can just simply use i instead of flag. But I'd actually use k instead of i or j, which are the imaginary variable.
  댓글 수: 3
Image Analyst
Image Analyst 2016년 3월 30일
No, more like this:
for index = 1 : 3
data = GetData(index); % Somehow get a new value for data.
theMeans(index) = mean_value(data);
end
Ann G
Ann G 2016년 3월 30일
Unfortunately, it doesn't work..I get this message: ??? In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in ==> main_code_multiple_save at 129 theMeans(t)=mean_value(data);

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by