A triangular creation in a matrix with the rest zeros
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I want to write a code which does the following:
Say its input is 'n = 12' to create a matrix arranged triangularly with the rest zeros (Only use loop), for example:
% code
Input: n = 12
Output: mat = [1 0 0 0
2 3 0 0
4 5 6 0
7 8 9 10
11 12 0 0]
Thank you
4 Kommentare
dpb
am 20 Mai 2018
What if you were to start with an array of the proper final size containing (let me guess...) zeros, maybe?
Akzeptierte Antwort
Jan
am 20 Mai 2018
you do not have to run the loop from 1 to n, but only until all rows have been created.
n = input('Enter a number');
s = 1;
mat = [];
k = 1;
while s <= n
g = s : s + k - 1; % No square brackets needed. a:b:c is a vector already
g = g(g <= n);
s = s + k;
k = k + 1;
mat(k, 1:length(g)) = g;
end
Or create g with the maximum length directly - then omit g=g(g<=n):
g = s : min(n, s + k - 1);
You could pre-allocate mat by zeros() also. This would be more efficient that letting the array grow iteratively, but run time is not the problem in this question. But you could replace the while loop by a simpler for loop, if you know the number of rows in advance.
rows = ceil((sqrt(8 * n + 1) - 1) / 2)
Try this to create a for k = 1:rows loop.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!