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 件のコメント

KSSV
KSSV 2022 年 12 月 5 日
How index can be 0? Index cannot be zero. Your question is not clear though.
Raahim Muzaffar
Raahim Muzaffar 2022 年 12 月 5 日
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
Walter Roberson 2022 年 12 月 5 日
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 件のコメント

Raahim Muzaffar
Raahim Muzaffar 2022 年 12 月 5 日
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

サインインしてコメントする。

その他の回答 (1 件)

Voss
Voss 2022 年 12 月 5 日

0 投票

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by