A triangular creation in a matrix with the rest zeros

1 view (last 30 days)
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 Comments
Emilia
Emilia on 20 May 2018
Ok I'm sorry, thanks for sending a link.
Yes it was taken from the homework (Problem 44457), I wrote a code for a triple matrix (without zeros) and here i need help how to place zeros (rest) within the triangular matrix to get a new matrix.
% code
n=input('Enter a number');
s = 1;
for k = 1 : n
g=[s : s + k - 1];
s = s + k;
b=(g<=n);
m=g(b);
end
After receiving code
1
2 3
4 5 6
7 8 9 10
11 12
dpb
dpb on 20 May 2018
What if you were to start with an array of the proper final size containing (let me guess...) zeros, maybe?

Sign in to comment.

Accepted Answer

Jan
Jan on 20 May 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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!