Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Can anyone tell me what is wrong with this loop? It fails on the second line. I believe the functions are correct bc they work in the command line.

조회 수: 1 (최근 30일)
for i = 1:(n)
a(i+1) = a(i) - (ss(a(i)))/(ssp(a(i)))
end
  댓글 수: 1
Ced
Ced 2016년 4월 16일
how is a initialized? What about n? And what are ss and ssp? What does the error say?

답변 (2개)

Peter O
Peter O 2016년 4월 17일
편집: Peter O 2016년 4월 17일
As Ced says, some additional context would be helpful to answer the question completely.
You say it works form the command line, but not in a function. My hunch is that it's either a variable initialization issue or non-integer addressing issue.
Your loop attempts to address indices of the variables ss and ssp at the positions in them given by a(i), which comes from the prior loop value. If ss and ssp aren't sized appropriately and the number at a(i) is larger than the size of ss or ssp MATLAB is going to complain. It may be that they have different values in the base workspace (seen from the command line) than what they get in the function. I know I've done this before.
Check also for a non-integer address issue. Whatever is in ss at a(i) is being divided by the a(i)th value of ssp to create a new address position. If this is not an integer then MATLAB will not like it. Similarly, if the subtraction results in a number less than or equal to zero, you'll get an error. You can deal with the fraction problem using a function like round(), ceil() or floor(), although I don't know the specifics of what you're computing to judge whether that's an acceptable solution.

Image Analyst
Image Analyst 2016년 4월 17일
You need to initialize a, so that when the first iteration happens a(1) has some value in it:
a = 10; % Whatever you want
% Now do the for loop
for i = 1 : n

Community Treasure Hunt

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

Start Hunting!

Translated by