Replacing each array element with a series of values

조회 수: 1 (최근 30일)
Varun Nair
Varun Nair 2017년 4월 25일
댓글: Varun Nair 2017년 4월 29일
Hi, I have a a 1 x N matrix of numbers. For example, a matrix T:
T = [1 4 7]
I would like to convert T to the new matrix as follows:
T_new = [1 2 3 4 5 6 7 8 9]
Basically, each element of T is replaced by an arithmetic series of 3 values with that element as the starting element and common difference = 1.
I tried
T_new = [T:T+3];
But it only updates the first element (I get T_new = [1 2 3 4]). Is there any quick way to do this without using a for loop ?
Thanks.

채택된 답변

Stephen23
Stephen23 2017년 4월 25일
>> T = [1,4,7];
>> cell2mat(arrayfun(@(n)n+(0:2),T,'uni',0))
ans =
1 2 3 4 5 6 7 8 9

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2017년 4월 25일
편집: Andrei Bobrov 2017년 4월 25일
T_new = reshape(T(:)' + (0:2)',1,[])
  댓글 수: 3
Andrei Bobrov
Andrei Bobrov 2017년 4월 26일
You are using an older version of MATLAB.
Variant for you:
T_new = reshape(bsxfun(@plus,T(:)',(0:2)'),1,[])
Varun Nair
Varun Nair 2017년 4월 29일
Yup, this works. Thanks !

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


dbmn
dbmn 2017년 4월 25일
One possible solution would be:
0. having
T = [1 4 7];
1. create a temporary matrix T_temp that looks like (this could be done in a loop very easily)
T_new = [1 2 3;
4 5 6;
7 8 9 ];
2. then reshape that matrix using
T_new=reshape(T_tmp', 1, numel(T_tmp));
1 2 3 4 5 6 7 8 9
  댓글 수: 1
Varun Nair
Varun Nair 2017년 4월 25일
편집: Varun Nair 2017년 4월 25일
Thanks, but, as I mentioned in the question, I was looking for a way to do it without using a for loop (i.e. without having to loop through all elements).

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

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by