Hi everyone,
Suppose I have matrix A
A = [1; 2; 3; 4]
And I want to have matrix B
B = [1; 1; 2; 1; 2; 3; 1; 2; 3; 4]
I don't want to use loop to do so because I have lots of observations. So how can I do this efficiently without using loop? Thank you very much!
Jeff

댓글 수: 5

Stephen23
Stephen23 2017년 1월 19일
@Tsz Heung: what is the rule to generate B from A ?
Tsz Heung
Tsz Heung 2017년 1월 19일
What do you mean? My question is how can I generate B from A.
Adam
Adam 2017년 1월 19일
I assume the rule is you want just the 1st row, then the first 2 rows, then the first 3 rows, etc, all collapsed into a single vector.
Jan
Jan 2017년 1월 19일
@Tsz Heung: There is an infinite number of methods to create B based on A from your example. To create a program, we have to know the definition of the procedure. One example is not enough to define this unequivocally.
@Adam: You mean:
  • one time the first row
  • one time the first 2 rows
  • two times the first 3 rows
  • one time the last row
???
Adam
Adam 2017년 1월 19일
편집: Adam 2017년 1월 19일
No, I meant
  • one time the first row,
  • one time the first 2 rows,
  • one time the first 3 rows,
  • one time the first 4 rows,...

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

 채택된 답변

Stephen23
Stephen23 2017년 1월 19일
편집: Stephen23 2017년 1월 19일

2 개 추천

There are most likely much more efficient algorithms than this:
>> N = 4;
>> X = (1:N)'*ones(1,N);
>> X(triu(true(N)))
ans =
1
1
2
1
2
3
1
2
3
4
You can use X as indices into your vector to select the values that you want.

댓글 수: 2

Jan
Jan 2017년 1월 19일
+1: An excellent guess.
Tsz Heung
Tsz Heung 2017년 1월 19일
Really Appreciated! Thank you Stephen!

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 1월 19일

1 개 추천

nonzeros(triu(repmat(A,1,length(A))))
Note: this assumes that none of the entries are 0.

댓글 수: 2

Stephen23
Stephen23 2017년 1월 19일
편집: Stephen23 2017년 1월 19일
+1 very nice. It would be interesting to know if repmat or multiply is faster:
nonzeros(triu((1:N)'*ones(1,N)))
Tsz Heung
Tsz Heung 2017년 1월 19일
Really Appreciated! Thank you Walter!

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

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2017년 1월 19일

댓글:

2017년 1월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by