Equation in a loop that feeds an answer matrix
조회 수: 4 (최근 30일)
이전 댓글 표시
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
채택된 답변
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);
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!