How to use while loop in matrix?
조회 수: 22 (최근 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!