Clear Filters
Clear Filters

Info

This question is closed. Reopen it to edit or answer.

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 view (last 30 days)
for i = 1:(n)
a(i+1) = a(i) - (ss(a(i)))/(ssp(a(i)))
end

Answers (2)

Peter O
Peter O on 17 Apr 2016
Edited: Peter O on 17 Apr 2016
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 on 17 Apr 2016
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!