# 1x10 matrix using a single while loop

9 visualizzazioni (ultimi 30 giorni)
Mary Jean Savitsky il 5 Ott 2020
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 CommentoMostra NessunoNascondi Nessuno
Walter Roberson il 5 Ott 2020
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.

Accedi per commentare.

### Risposta accettata

Pink_panther il 5 Ott 2020
n=10;A =zeros(1,n);k=1;
while k <=n
A(k)=k
k=k+1;
end
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Più risposte (2)

Walter Roberson il 5 Ott 2020
variable = initial_value;
while variable <= final_value
do something with variable
variable = variable + increment;
end
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

Pink_panther il 5 Ott 2020
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 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
Walter Roberson il 5 Ott 2020
The poster asked for exactly one while loop, but did not ask for a one-liner.

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!