I need to combine two channels of cell arrays into a single matrix for processing. The two channels should be the same size but in some cases not - how can I change the size?

channelData = cell(2, 1);
........
I have tried code like this but it states the concatenation dimesnions are inconsistent:
% Ensure both channels have the same number of samples
numSamplesCh1 = length(channelData{1});
numSamplesCh2 = length(channelData{2});
if numSamplesCh1 > numSamplesCh2
numSamplesCh1 = numSamplesCh2;
mycell = trimdata(channelData,numSamplesCh1);
else
numSamplesCh2 = numSamplesCh1;
mycell = trimdata(channelData,numSamplesCh2);
end
combinedData = [channelData{1}, channelData{2}];
The above code combines the channels but in some cases they are wrong size. How can I resize the ChannelData{1} and ChannelData{2} so they are the smallest size of the two (please)?

 採用された回答

Voss
Voss 2024 年 11 月 6 日
編集済み: Voss 2024 年 11 月 7 日
Assuming that channelData is a 2-element cell array, that channelData{1} and channelData{2} are both column vectors, and you want to combine them into a matrix with two columns, then you can use trimdata to do so like this:
% n: length of shorter vector
% idx: index (1 or 2) of shorter vector in channelData
[n,idx] = min([numel(channelData{1}) numel(channelData{2})]);
% trim the longer vector (3-idx makes 1 become 2 and vice versa) to length n
channelData{3-idx} = trimdata(channelData{3-idx},n);
% combine the vectors into an n-by-2 matrix
combinedData = [channelData{:}];
If you don't want to overwrite channelData, then use a temporary variable instead:
tmp = channelData;
tmp{3-idx} = trimdata(tmp{3-idx},n);
combinedData = [tmp{:}];
Your mistake was using trimdata to trim the cell array channelData itself rather than the contents of one of its cells (i.e., channelData{1} or channelData{2}, whichever is longer). That and not using the assigned output mycell, so that you were not actually modifying channelData at all before attempting to concatenate its contents.

2 件のコメント

Thank you Voss for your indepth answer - This is what happens when you come in and out of coding for long periods of time........you become very rusty! ;-) Maths and languages are the same!
I really do appreicate the long, indepth answer as it has helped me a lot.
Ultinmately, thank you for your selfless attitude it is most appreciated! Have a great day to day.
Kind regards,
James
Voss
Voss 2024 年 11 月 7 日
You're welcome!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

リリース

R2023b

質問済み:

2024 年 11 月 6 日

編集済み:

2024 年 11 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by