Azzera filtri
Azzera filtri

How do I add 0 after every value in a vektor

5 visualizzazioni (ultimi 30 giorni)
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 Commento
Walter Roberson
Walter Roberson il 25 Feb 2022
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)

Accedi per commentare.

Risposta accettata

Image Analyst
Image Analyst il 25 Feb 2022
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

Più risposte (1)

Jan
Jan il 25 Feb 2022
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 Commento
Luqas Lundahl
Luqas Lundahl il 25 Feb 2022
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!

Accedi per commentare.

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by