フィルターのクリア

Fill an array with different size vectors

49 ビュー (過去 30 日間)
Diego R
Diego R 2019 年 9 月 5 日
コメント済み: Aena 2022 年 12 月 26 日
I have different sized vectors and an array to fill
A=[1,2,3,4];
B=[5,6];
C=[7,8,9];
ARRAY=zeros(5);
And I want to reach this:
OBJECTIVE =
1 2 3 4 0
5 6 0 0 0
7 8 9 0 0
0 0 0 0 0
0 0 0 0 0
Any idea? Also if there is any way to extend vectors to certain length I highly appreciate to know.

採用された回答

Stephen23
Stephen23 2019 年 9 月 5 日
編集済み: Stephen23 2019 年 9 月 5 日
For an arbitrary number of vectors use a cell array, then looping is trivial:
>> D = {[1,2,3,4],[5,6],[7,8,9]};
>> M = zeros(5,5);
>> for k = 1:numel(D), M(k,1:numel(D{k})) = D{k}; end
>> M
M =
1 2 3 4 0
5 6 0 0 0
7 8 9 0 0
0 0 0 0 0
0 0 0 0 0

その他の回答 (3 件)

the cyclist
the cyclist 2019 年 9 月 5 日
Here is one straightforward way:
A=[1,2,3,4];
B=[5,6];
C=[7,8,9];
ARRAY=zeros(5);
ARRAY(1,1:numel(A)) = A;
ARRAY(2,1:numel(B)) = B;
ARRAY(3,1:numel(C)) = C;
  1 件のコメント
Aena
Aena 2022 年 12 月 26 日
it works. Thanks!

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


Diego R
Diego R 2019 年 9 月 5 日
Thank you both! I'd never had found this "numel" by myslef.

Jos (10584)
Jos (10584) 2019 年 9 月 5 日
A=[1,2,3,4];
B=[5,6];
C=[7,8,9];
[ARRAY, tf] = padcat(A,B,C) % pad with NaNs
ARRAY(~tf) = 0 % replace those NaNs with zeros
PADCAT concatenates vectors of unequal lengths by padding them with NaNs. It is available for free on the File Exchange

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by