I am trying to create this matrix ; How can i do this using for loops or without loops?

1 visualizzazione (ultimi 30 giorni)
A=[0 0 0 0 0 0 0 0 0 ; 1 1 1 0 0 0 0 0 0 ; 1 1 1 1 1 1 0 0 0 ];

Risposte (1)

John D'Errico
John D'Errico il 7 Apr 2022
Modificato: John D'Errico il 7 Apr 2022
Without loops? Trivial.
A=[0 0 0 0 0 0 0 0 0 ; 1 1 1 0 0 0 0 0 0 ; 1 1 1 1 1 1 0 0 0 ];
A
A = 3×9
0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0
As you can see, that works nicely. Why would you need any other way? Yes. There are surely ways you could do it. But why would you use loops? Yes, I suppose you could do this:
B = ones(3,9);
B(1,1) = 0;
B(2,4) = 0;
B(3,7) = 0;
B = cummin(B,2);
B
B = 3×9
0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0
Or you might have done this:
C = zeros(3,9);
C(2,1:3) = 1;
C(3,1:6) = 1;
C
C = 3×9
0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0
And I could easily come up with a million other ways.
But if you are looking for some elegant, magical way to solve the problem, when a perfectly good, inelegant solution exists, don't bother.
The art of programming is NOT about elegance, not about beauty. The art of programming is to get the job done. NOW. Don't waste your time looking for an elegant solution when an inelegant one exists that is perfectly adequate. Only if the solution you have is too slow or a problem for some reason do you look further.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by