1x10 matrix using a single while loop
조회 수: 3 (최근 30일)
이전 댓글 표시
n = 10;
A =zeros(1,n);
count=1;
while i==1 && j==1:n;
count=count+1;
A(i,j)=count;
end
display(A)
trying to get this to display A=[1 2 3 4 5 6 7 8 9 10] using exactly 1 while loop.
댓글 수: 1
Walter Roberson
2020년 10월 5일
while i==1 && j==1:n;
j==1:n is a vector comparison, with a vector result (length 10). You cannot use a vector together with the && operator.
Also, your while loop does not change i or j, so your loop would be infinite if it was accepted at all.
채택된 답변
추가 답변 (2개)
Walter Roberson
2020년 10월 5일
variable = initial_value;
while variable <= final_value
do something with variable
variable = variable + increment;
end
댓글 수: 0
Pink_panther
2020년 10월 5일
OP was asking for one liner.
Here is the shorter verion, it worked on my PC.
n=10;A=[];k=1;while k <=n,A=cat(2,A,k),k=k+1;end
댓글 수: 2
Rik
2020년 10월 5일
You didn't format this as code, and it actually performs worse than your other answer, because it dynamically grows the array. Other than that it is identical to your other answer. What would be the benefit? Compressing code into a one-liner doesn't usually improve code readibility and doesn't change performance.
Walter Roberson
2020년 10월 5일
The poster asked for exactly one while loop, but did not ask for a one-liner.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!