How to implement the output matrix without if conditions

5 次查看(过去 30 天)
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.

更多回答(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