# Populate a column vector with values from another column vector

2 views (last 30 days)
Raahim Muzaffar on 5 Dec 2022
Commented: Walter Roberson on 5 Dec 2022
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 CommentsShowHide 1 older comment
Raahim Muzaffar on 5 Dec 2022
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

Walter Roberson on 5 Dec 2022
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
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 CommentsShowHide 1 older comment
Walter Roberson on 5 Dec 2022
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

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