How to implement the output matrix without if conditions

5 Ansichten (letzte 30 Tage)
Shuoze Xu
Shuoze Xu am 2 Jul. 2022
Kommentiert: KSSV am 2 Jul. 2022
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.

Akzeptierte Antwort

KSSV
KSSV am 2 Jul. 2022
Bearbeitet: KSSV am 2 Jul. 2022
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 Kommentare
Shuoze Xu
Shuoze Xu am 2 Jul. 2022
Thank you.
May you tell me what is meaing of iwant, Is it just a variable?
KSSV
KSSV am 2 Jul. 2022
It is supposed to be A. I have edited the answer.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by