Populate a column vector with values from another column vector

Hey!
I have a column vector A that is 1x50 that contains values
I want to populate a 1x57 zero column vector B with the values of A at a certain index.
E.g. At index 0,1,2,5,7,8,11 should all be 0 - the other values of vector B should be populated from the non-zero values in vector A. How do i go about doing this?

2 commentaires

How index can be 0? Index cannot be zero. Your question is not clear though.
Sorry I'm getting used to matlab syntax. By index = 0 i mean first element in the array.
To be more specific, I have:
Column vector A that is 1x50.
Column vector B that is 1x57.
I want the values of the first element in B, second element in B, third element in B, 6th element in B, 8th element in B, 9th element in B, 12th element in B to all be zero. I want the rest of the 50 values to be the values specified in Column Vector A. Hope this is more clear

Connectez-vous pour commenter.

 Réponse acceptée

A = randi(9, 1, 50);
zeros_at = [0,1,2,5,7,8,11];
B = zeros(1, numel(A) + length(zeros_at));
mask = ismember((0 : length(B)-1), zeros_at);
B(~mask) = A;
B
B = 1×57
0 0 0 6 9 0 6 0 0 7 5 0 5 3 6 7 7 7 7 6 7 8 7 6 9 2 7 4 1 9

2 commentaires

Thank you!!!!!!!!
Marginally different approach:
A = randi(9, 1, 50);
zeros_at = [0,1,2,5,7,8,11];
B = zeros(1, numel(A) + length(zeros_at));
idx = setdiff(1:length(B), zeros_at+1);
B(idx) = A
B = 1×57
0 0 0 4 8 0 2 0 0 5 9 0 9 3 7 5 7 9 8 3 3 5 8 2 5 7 1 2 1 8

Connectez-vous pour commenter.

Plus de réponses (1)

B = zeros(57,1); % 57x1 column vector
B([4 5 7 10 11 13:end]) = A;

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by