How do I add 0 after every value in a vektor

조회 수: 9 (최근 30일)
Luqas Lundahl
Luqas Lundahl 2022년 2월 25일
댓글: Luqas Lundahl 2022년 2월 25일
So i have to add 0 after every value in a vektor. The vektor is decided by the user and im trying to use 'for' in the solution.
for example if my vektor is v=[3,5,2,7] the new vektor should be u=[3,0,5,0,2,0,7,0]
what ive come up with so far, i don't know how to use the 'for' command and im trying to learn
v=input('add a vektor of your choosing: ');
u=zeros(1,2*length(v));
for
????
????
end
disp(['The new vektor is [' num2str(u) ']'])
so far i tried replacing the ?? with
n=1:2:length(v);
v(n)=u;
but got the error msg "Unable to perform assignment because the left and right sides have a different number of elements."
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 2월 25일
Hint:
v(1) gets written to u(1)
v(2) gets written to u(3)
v(3) gets written to u(5)
so each increment by 1 in the index of v, results in an increment by 2 in the index of u
u(2*n + something) = v(n)

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

채택된 답변

Image Analyst
Image Analyst 2022년 2월 25일
Try this:
v=[3,5,2,7];
for k = 1 : length(v)
index = (k-1) * 2 + 1;
u(index) = v(k);
end
% Add final trailing 0
u(end+1) = 0 % Show in command window.
u = 1×8
3 0 5 0 2 0 7 0

추가 답변 (1개)

Jan
Jan 2022년 2월 25일
This works without a loop.
v = [3,5,2,7];
Now append a 2nd row with zeros:
v = [v; zeros(size(v))];
% Or equivalently:
v(2, :) = 0;
Remember, that Matlab stores values of arrays in column order. Then:
v(:)
is almost what you want to get. Just transpose it.
Alternative is to create a vectore of zeros in the wanted length:
w = zeros(1, numel(v) * 2);
Now fill the indices 1:2:numel(w) with the elements of v. There is no need for a loop and your "n=1:2:length(v); v(n)=u;" is almost correct.
  댓글 수: 1
Luqas Lundahl
Luqas Lundahl 2022년 2월 25일
Thanks you for the answer! However, I'm specifically using 'for' because i want to learn how it works so i can use it more efficiently in the future, so i want my code to include it! If you can help me i would really appriciate it!

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by