Equation in a loop that feeds an answer matrix

조회 수: 4 (최근 30일)
Tomas White
Tomas White 2022년 5월 3일
답변: Voss 2022년 5월 3일
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
Voss 2022년 5월 3일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by