How to use while loop in matrix?

18 次查看(过去 30 天)
Bora Egüz
Bora Egüz 2020-5-24
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. :)

回答(1 个)

Ameer Hamza
Ameer Hamza 2020-5-24
编辑:Ameer Hamza 2020-5-24
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by