How do I add 0 after every value in a vektor
조회 수: 9 (최근 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
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
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.
추가 답변 (1개)
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!