How to implement the output matrix without if conditions
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!