Equation in a loop that feeds an answer matrix
1 view (last 30 days)
Show older comments
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);
0 Comments
Accepted Answer
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);
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);
Of course, if that's all the loop does, that can be done in one line:
results = 90/n*(1:n)
or, if s is the variable you're calculating:
s = 90/n*(1:n)
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!