How to use while loop in matrix?
18 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!