Filter löschen
Filter löschen

How do I add 0 after every value in a vektor

4 Ansichten (letzte 30 Tage)
Luqas Lundahl
Luqas Lundahl am 25 Feb. 2022
Kommentiert: Luqas Lundahl am 25 Feb. 2022
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 Kommentar
Walter Roberson
Walter Roberson am 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)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Image Analyst
Image Analyst am 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

Weitere Antworten (1)

Jan
Jan am 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 Kommentar
Luqas Lundahl
Luqas Lundahl am 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!

Melden Sie sich an, um zu kommentieren.

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by