Too many inputs to CFIT/SUBSREF.error when using a for loop

조회 수: 18 (최근 30일)
Robbie McDermott
Robbie McDermott 2017년 12월 11일
댓글: Kensington Hartman 2022년 4월 4일
I have the following code:
image=a(:,:,n);
Isum=sum(image,1);
[Imax,Iloc]=max(Isum);
I=image(:,Iloc);
fit=fit(L,I,'exp1');
coeff=coeffvalues(fit);
coeff=coeff(1,2)
alpha=coeff;
This works well, and I can put in any number to, n, to get the file I need however when I run this in a for loop to access all values of n, (1:20) it tells me there is a "Error using cfit/subsref>iParenthesesReference (line 36) Too many inputs to CFIT/SUBSREF." error The error occurs on line "fit=fit(L,I,'exp1'); "
Any help would be greatly appreciated!
  댓글 수: 1
qingyun liu
qingyun liu 2018년 6월 18일
hey I have the same problem, and I have struggled for hours. Dont know why, hope somebody can come and answer your question

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

답변 (2개)

Kensington Hartman
Kensington Hartman 2022년 4월 4일
Hey there! I realize it's been 5 years so you may have moved on from this, but in case anyone else out there has the same question, I've found that it works as long as I clear the variable 'fit' at the end of the loop. So basically:
for i = 1:n
% Do something to get x and y
fit = fit(x,y,fitType);
clearvars fit; %this line clears fit from the active workspace
end
I'm new to Matlab and not very experienced with computers and coding in general, so I don't know why this is necessary, but it seems to work :)
  댓글 수: 2
Voss
Voss 2022년 4월 4일
The line:
fit = fit(x,y,fitType);
runs the function fit and stores the result in a variable called fit. Then the next time you want to run the fit function, you cannot because fit now refers to the variable fit instead. Clearing the variable allows you to run the fit function again since there is no longer a variable with the same name.
It is best to avoid naming variables with the same names as functions, so you might do this instead:
for i = 1:n
% Do something to get x and y
my_fit = fit(x,y,fitType);
end
i.e., use my_fit as the variable name, and there is no need to clear it each time (it doesn't conflict with the function fit).
Kensington Hartman
Kensington Hartman 2022년 4월 4일
Ahhh that makes a lot of sense, thank you!

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


Steven Lord
Steven Lord 2022년 4월 4일
As long as there is a variable named fit it takes precedence over the function named fit, preventing you from calling the function.
In general you should avoid defining variables with the same name as a function.
plot = 50:60;
plot(1:10) % Does not open a figure and create graphics. This indexes into the plot variable.
ans = 1×10
50 51 52 53 54 55 56 57 58 59

카테고리

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