# Equation in a loop that feeds an answer matrix

1 view (last 30 days)
Tomas White on 3 May 2022
Answered: Voss on 3 May 2022
Hello! I have this non loop code that I have been trying to turn it into a loop (so I can assign different values to "n" if I want to) but I can´t seem to figure it out. Any help is parreciated.
% Equation structure:
% s(i)=(90/n)*(i)
%with no loop
station=[1,2,3,4,5,6,7];
s1=(90/7)*1;
s2=(90/7)*2;
s3=(90/7)*3;
s4=(90/7)*4;
s5=(90/7)*5;
s6=(90/7)*6;
s7=(90/7)*7;
results=[s1,s2,s3,s4,s5,s6,s7];
%With a loop
n=7 %station number
results=[]
while (i <= n)
s(i)=(90/n)*(i);
i = i+1 ;
end
s=results;
disp(results);

Voss on 3 May 2022
It seems like you should be setting an element of results instead of s each time through the loop:
%With a loop
n=7; %station number
results=[];
i = 1; % initialize i to 1
while (i <= n)
results(i)=(90/n)*(i);
i = i+1 ;
end
% s=results;
disp(results);
12.8571 25.7143 38.5714 51.4286 64.2857 77.1429 90.0000
Or maybe you mean to assign s to results (instead of assigning results to s) after the loop:
%With a loop
n=7; %station number
results=[];
i = 1; % initialize i to 1
while (i <= n)
s(i)=(90/n)*(i);
i = i+1 ;
end
% s=results;
results = s;
disp(results);
12.8571 25.7143 38.5714 51.4286 64.2857 77.1429 90.0000
Of course, if that's all the loop does, that can be done in one line:
results = 90/n*(1:n)
results = 1×7
12.8571 25.7143 38.5714 51.4286 64.2857 77.1429 90.0000
or, if s is the variable you're calculating:
s = 90/n*(1:n)
s = 1×7
12.8571 25.7143 38.5714 51.4286 64.2857 77.1429 90.0000

R2020a

### Community Treasure Hunt

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

Start Hunting!