How to use while loop in matrix?
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello, i have this question:
A=zeros(5,8);
Let A(i,j) be the (i,j)th element of A, where i=1,2,,..5 and j=1,2,...8. Use a while loop to replace each element of A in the following way.
If i>j set A(i,j)=4*i-2j.
If i<=j set A(i,j)=i^2-3j.
For now i try this code to solve
B=zeros(5,8);
k=1;
l=1;
while not(l==9)
if k>l
B(k,l)=4*k-2*l;
else
B(k,l)=k^2-3*l;
end
l=l+1;
end
B
I get the result for only first row and I dont know how to make this calculations for the other rows with while func. I know how to do with for loop but I couldnt figure it out to do iteration in while func.
Thanks for helping. :)
0 Kommentare
Antworten (1)
Ameer Hamza
am 24 Mai 2020
Bearbeitet: Ameer Hamza
am 24 Mai 2020
Here is a solution without for-loop
A = zeros(5,8);
[i, j] = ndgrid(1:size(A,1), 1:size(A,2));
A = (4*i-2*j).*(i>j) + (i.^2-3*j).*(i<=j);
Result
>> A
A =
-2 -5 -8 -11 -14 -17 -20 -23
6 -2 -5 -8 -11 -14 -17 -20
10 8 0 -3 -6 -9 -12 -15
14 12 10 4 1 -2 -5 -8
18 16 14 12 10 7 4 1
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!