필터 지우기
필터 지우기

How to insert an element after each number in a vector?

조회 수: 15 (최근 30일)
laith Farhan
laith Farhan 2019년 5월 5일
댓글: Star Strider 2019년 5월 5일
Dear all,
I would like to add an element after each value in a vector, for example:
a=[10,2,40,58,100,90,40,30,4];
I would like to add 1 to vector values:
result = [1,10,1,2,1,40,1,58,1,100,1,90,1,40,1,30,1,4,1];
Help me please.....
  댓글 수: 1
Image Analyst
Image Analyst 2019년 5월 5일
Instead of "after each number" don't you mean "after each number, EXCEPT the first number, where the number is also before the first number?" That's what Star and Adams solutions do. Or do you really mean what you said, instead of the "result" you gave, and so there would be no 1 at the beginning?

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

채택된 답변

Star Strider
Star Strider 2019년 5월 5일
One approach:
a=[10,2,40,58,100,90,40,30,4];
result = [ones(size(a)); a];
result = [result(:); 1]'
producing:
result =
1 10 1 2 1 40 1 58 1 100 1 90 1 40 1 30 1 4 1
  댓글 수: 4
laith Farhan
laith Farhan 2019년 5월 5일
Super thanks Star Strider. It is really nice solution.
Thanks a lot guys for your solution and suggestion, I really appreciate that.
Star Strider
Star Strider 2019년 5월 5일
As always, my pleasure!

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

추가 답변 (2개)

Adam Danz
Adam Danz 2019년 5월 5일
result = [reshape([ones(size(a));a],length(a)*2,1);1]';
  댓글 수: 3
KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 5월 5일
편집: KALYAN ACHARJYA 2019년 5월 5일
Nice one, +1, I tried, but can't
laith Farhan
laith Farhan 2019년 5월 5일
Thanks Adam Danz. I really apprecaite your help.

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


Image Analyst
Image Analyst 2019년 5월 5일
Instead of "after each number" did you mean "after each number, EXCEPT the first number, where the number is also before the first number?" That's what Star and Adam's solutions do. Or do you really mean what you said, instead of the "result" you gave, and so there would be no 1 at the beginning?
Just to be complete and cover all ambiguities, I'll give the other solution. If you really want what you said in words, rather than the numerical result you gave, then use this code:
result = [a; ones(size(a))]
result = result(:)'
The result is:
result =
10 1 2 1 40 1 58 1 100 1 90 1 40 1 30 1 4 1
Note: 1's are only after the numbers and not before the first one.
  댓글 수: 1
laith Farhan
laith Farhan 2019년 5월 5일
Thanks Image Analyst, yes, it might help me for another cases.

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

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by