subscript indices must either be real positive integers or logicals when using a function in a nested for?
1 次查看(过去 30 天)
显示 更早的评论
I use this function in a nested for and I get this error: subscript indices must either be real positive integers or logicals
Zpred = h(Xpred)
where Xpred is a matrix
function zk=h(x)
zk(1,:)=sqrt(900+(x(1,:)-30).^2);
zk(2,:)=x(2,:).*(x(1,:)-30)./zk(1,:)
can anyone help me to find the error
1 个评论
Joseph Cheng
2015-5-28
function zk=h(x)
zk(1,:)=sqrt(900+(x(1,:)-30).^2);
zk(2,:)=x(2,:).*(x(1,:)-30)./zk(1,:)
采纳的回答
Image Analyst
2015-5-28
I think the FAQ explains it really well: http://matlab.wikia.com/wiki/FAQ#How_do_I_fix_the_error_.22Subscript_indices_must_either_be_real_positive_integers_or_logicals..22.3F
When you're calling this:
Zpred = h(Xpred)
at that point, it thinks h is an array, not a function like you thought.
Your script/function is not called h.m is it? Or else somethere else earlier in your code, you must have used h in a way that created an array called h.
更多回答(1 个)
Joseph Cheng
2015-5-28
编辑:Joseph Cheng
2015-5-28
so when i run the code you have:
function zk=h(x)
zk(1,:)=sqrt(900+(x(1,:)-30).^2);
zk(2,:)=x(2,:).*(x(1,:)-30)./zk(1,:);
with the input
h(randi(10,2,1))
i don't get the error. Now with this type of error the fastest thing is for you to use the debugger and solve it. Put a breakpoint at the call, verify the input Xpred is actually what you want, there is no variable or other item already called h, and if everything checks out step inside the function where is the line that the error says it is?
3 个评论
Joseph Cheng
2015-5-28
编辑:Joseph Cheng
2015-5-28
you should not use 'h' to describe a function and a variable. Matlab is not smart enough to understand which one you're trying to use.
Here is an example: if my dog is called Brian and I have a friend called Brian, and I ask you to take Brian outside. You wouldn't not know which one to take out side would you? Call your function another name or use another variable name for h.
*sorry to anyone named Brian. It was the first name i could think of.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!