필터 지우기
필터 지우기

A triangular creation in a matrix with the rest zeros

조회 수: 2 (최근 30일)
Emilia
Emilia 2018년 5월 20일
댓글: Emilia 2018년 5월 21일
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
Emilia
Emilia 2018년 5월 20일
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 2018년 5월 20일
What if you were to start with an array of the proper final size containing (let me guess...) zeros, maybe?

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2018년 5월 20일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by