Asked by Kokalz
on 19 Jul 2012

Hi Guys! I am writing a GUI that processes some excel data and got to a point, where I need it to do some loop calculation. However, I have absolutely no idea how to do it. I tried going through all Doug's tutorials, but could not find anything, that would explain it. So here's the idea:

Say i need a 1x20 matrix. I know the first value of this vector, but all he other values come from the calculations that require the first value. So here's the sequence of the calculation:

Take the first value > input it into formulas with other variables > get the second value > use the second value to get the 3 rd value > get the 3rd value > use the 3rd value to get the 4th value > and so on.... Then plot all the acquired values on the graph against time.

Could someone help me out with it? Tell me if I made i too confusing..

Thank you, guys!

Answer by Thomas
on 19 Jul 2012

Probably something like this..

num_values=10; % total values

first_val=2;

output=zeros(1,num_values); %preallocate space for output

output(1)=first_val; % first value of output

for count=2:num_values

output(count)=output(count-1)+25; %formula current value depends on previous

end

output

plot(output)

Sign in to comment.

Answer by Ryan
on 19 Jul 2012

So you have a 1 x 20 vector you want to fill off of knowing just the first value and each previously value determines the next? Is this what you're looking for:

t = 1:1:20; % for graphing later

x = zeros(1,20);

x(1) = .5; % Assign first value of "x"

for m = 2:numel(x)

x(m) = sin(x(m-1)); % Calculates the current cell "m" off of prior cell "m-1"

end

figure,plot(t,x)

Sign in to comment.

Answer by C.J. Harris
on 19 Jul 2012

Here is an example of a quick loop that calculates a value based on the previous value. The loop simply calculates the value as twice the previous value:

A = zeros(1,20); % Initialize array

A(1) = 1; % Set first value to 1

for nLoop = 2:length(A) % Start loop at second value

A(nLoop) = A(nLoop-1) * 2; % Answer is twice the previous value

end

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## NUR ZAFIRAH MOHD SIDEK (view profile)

Direct link to this comment:https://de.mathworks.com/matlabcentral/answers/44032-how-to-create-a-loop-calcualtion#comment_462958

Sign in to comment.