How to use while loop in matrix?
15 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Ameer Hamza
on 24 May 2020
Edited: Ameer Hamza
on 24 May 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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!