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 Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by