How to implement the output matrix without if conditions

조회 수: 5 (최근 30일)
Shuoze Xu
Shuoze Xu 2022년 7월 2일
댓글: KSSV 2022년 7월 2일
Hi.
This is a review problem that requires the use of nested loops to output the following matrix.
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
Here is my code, i use the complex if statement to output.
matrix = []; % create empty matrx
nums = 0; % set a variable named nums and euqal to zero
nums_three = 3;
nums_four = 4;
nums_five = 5;
% use nested loop
for i = 1:5
for j = 1:i % the nums of columns will increase with the end of one outer loop
nums = nums + 1;
matrix(i,j) = nums;
if (i == 3)
matrix(i,j) = nums_three;
nums_three = nums_three+1;
elseif (i == 4)
matrix(i,j) = nums_four;
nums_four = nums_four+1;
elseif(i == 5)
matrix(i,j) = nums_five;
nums_five = nums_five + 1;
end
end
end
disp(matrix);
Here is my output
1 0 0 0 0
2 3 0 0 0
3 4 5 0 0
4 5 6 7 0
5 6 7 8 9
The first question i want to ask is that how can i remove zero in this matrx?
The second question is that Is there another way to output the matrix without using if- statement?
Thank you all.

채택된 답변

KSSV
KSSV 2022년 7월 2일
편집: KSSV 2022년 7월 2일
n = 5 ;
A = zeros(n) ;
for i = 1:n
for j = 1:i
A(i,j) = i+j-1 ;
end
end
A
You cannot remove zeros, if you want it as a matrix. Other option is you can replace zeros with NaNs.
  댓글 수: 2
Shuoze Xu
Shuoze Xu 2022년 7월 2일
Thank you.
May you tell me what is meaing of iwant, Is it just a variable?
KSSV
KSSV 2022년 7월 2일
It is supposed to be A. I have edited the answer.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by