Error in a matlab function
信息
此问题已关闭。 请重新打开它进行编辑或回答。
显示 更早的评论
Hello. i have a problem of dimension in this function:
function Generalized_coefficient= loggfc(alpha,n)
for m=1:1:n-1
f=[2:1:m-1];
g=[1:1:m-1];
x=[1:1:m+1];
Generalized_coefficient =logalpha;
a= log(m-alpha*f)+ Generalized_coefficient(f);
b=logalpha +Generalized_coefficient(g);
themax= max(a,b);
x(1)=log(m-alpha*1)+ Generalized_coefficient(1);
x(f)=themax+ log(exp(a-themax)+ exp(b-themax));
x(m+1)=logalpha+ Generalized_coefficient(m);
Generalized_coefficient=x;
end
end
When i put n=2; it's ok but when i set n=3 matlab provide me this error
"Attempted to access Generalized_coefficient(2); index out of bounds because numel(Generalized_coefficient)=1" How can i correct the code? Thank you
6 个评论
David Young
2015-1-15
Suggestions to help get an answer:
- If the answers to your previous questions were useful, accept them.
- Edit your code to remove the blank lines, and instead use the "{} Code" button to format it so that it is easy to read.
Geoff Hayes
2015-1-15
Elena - what is logalpha? Is it an input parameter or a local variable?
Elena
2015-1-15
dpb
2015-1-15
You can only "correct" the code by ensuring that there are at least as many elements in the array as your indexing expression tries to address.
The first pass f will be 2 so if numel() is only one as it says it was, then you're definitely outside the bounds of the array provided.
I can't decipher at all what it is that you expect/want this function to do in general so have no klew how to suggest rewriting it.
I suggest describe in plain words what your inputs are and expected/wanted outputs and probably someone can help in coding that. Sample input/output datasets are generally helpful.
Elena
2015-1-15
dpb
2015-1-15
You can't "modify" numel; it's the size of the array in the argument. Only changing that size/length of the array to be as long as the largest index or restricting the address to be within the actual length will cure the problem.
The difficulty is as described that it's not at all clear what your function is supposed to be doing since all we have is nonworking code; no description of what an expected output would be given an input.
回答(1 个)
Image Analyst
2015-1-15
"logalpha" is not defined. Perhaps you meant log(alpha).
Then, for n=2, m goes from 1 to 1, you say
f=[2:1:0]; % This will be empty.
a= log(m-alpha*f)+ Generalized_coefficient(f); % Kaboom!
so that will bomb - not sure why you said it doesn't.
Then, for n=2, m goes from 1 to 2, you say
f=[2:1:2]; % This will be 2.
a= log(m-alpha*f)+ Generalized_coefficient(f); % Kaboom!
Well, Generalized_coefficient does not have two elements yet. Luckily there is a way to solve this, and here it is.
0 个评论
此问题已关闭。
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!