How do I add 0 after every value in a vektor

6 次查看(过去 30 天)
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