combine different size vectors into one matrix

37 ビュー (過去 30 日間)
Suzuki
Suzuki 2021 年 9 月 17 日
コメント済み: Suzuki 2021 年 9 月 17 日
I need to combine sets of data I have together into one matrix, but they have different dimensions.
this is a simplified example:
e=[2 3 4 5];
>> ee=[4 7 7];
>> eee=[8 8 7 4 2 5];
>> p=[e; ee; eee];
I want to fill nan to make them even, but I don't know how.
I want each vector to be in a raw, so I get something like that
p=[2 3 4 5 NaN NaN;
4 7 7 NaN NaN NaN;
8 8 7 4 2 5];
then I want to get the mean for each column data
any suggestions please.

採用された回答

Chunru
Chunru 2021 年 9 月 17 日
編集済み: Chunru 2021 年 9 月 17 日
% use a cell array instead of separate variables
e{1}=[2 3 4 5];
e{2}=[4 7 7];
e{3}=[8 8 7 4 2 5];
% find the longest vector
l = max(cellfun(@(x) length(x), e))
l = 6
y = nan(length(e), l);
for i=1:length(e)
y(i, 1:length(e{i})) = e{i};
end
y
y = 3×6
2 3 4 5 NaN NaN 4 7 7 NaN NaN NaN 8 8 7 4 2 5
ym = mean(y, 1, 'omitnan') % mean along 1st dimension or column
ym = 1×6
4.6667 6.0000 6.0000 4.5000 2.0000 5.0000
  4 件のコメント
Chunru
Chunru 2021 年 9 月 17 日
See above.
Suzuki
Suzuki 2021 年 9 月 17 日
right, thanks alot.

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

その他の回答 (1 件)

Matt J
Matt J 2021 年 9 月 17 日
編集済み: Matt J 2021 年 9 月 17 日
I will assume you have the vectors in a cell array
C={[2 3 4 5];
[4 7 7];
[8 8 7 4 2 5]}
C = 3×1 cell array
{[ 2 3 4 5]} {[ 4 7 7]} {[8 8 7 4 2 5]}
Then, you can simply do,
z=max(cellfun('length',C));
p=cell2mat( cellfun(@(x)[x,nan(1,z-numel(x) )] ,C,'uni',0))
p = 3×6
2 3 4 5 NaN NaN 4 7 7 NaN NaN NaN 8 8 7 4 2 5
  1 件のコメント
Suzuki
Suzuki 2021 年 9 月 17 日
thank you very much.
I works, but it fill them all in one row.

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

カテゴリ

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