concatanate arrays upon condition
5 ビュー (過去 30 日間)
古いコメントを表示
Dear MatLAb Community,
I would like to concatanate selected coloumns of arrays, some of which are empty arrays, and this is varying dataset by dataset.
How can I exclude the empty arrays from concatanation?
Let's say now , distr3 and distr6 are empty but this my vary.
distr = cat(1,distr1(:,ch1),distr2(:,ch2),distr3(:,ch3),distr4(:,ch4),distr5(:,ch5),distr6(:,ch6),distr7(:,ch7),distr8(:,ch8));
Thans for you suggestions
BEst
lg
1 件のコメント
採用された回答
Matt J
2025 年 6 月 20 日
編集済み: Matt J
2025 年 6 月 20 日
The way your data is held, as separate enumerated variables, doesn't leave many options. The first thing would be to undo that:
distrCell = arrayfun(@(i)eval("distr"+i),1:8,'uni',0); %should be unnecessary
chCell = arrayfun(@(i)eval("ch"+i),1:8,'uni',0); %should be unnecessary
Then, you can do,
keep=~cellfun('isempty',distrCell);
distrCell=distrCell(keep);
chCell=chCell(keep);
distr=cell2mat( cellfun(@(d,c) d(:,c), distrCell,chCell ,'uni',0 ) )
2 件のコメント
Matt J
2025 年 6 月 20 日
編集済み: Matt J
2025 年 6 月 20 日
Modify along the following lines:
distr1=17; distr2=5; distr3=68;
distrCell = arrayfun(@(i)evalin('caller',"distr"+i),1:3,'uni',0) %should be unnecessary
Or, even better, recreate the data from scratch, but instead of distr1, distr2,... store the arrays in a distrCell variable directly.
その他の回答 (1 件)
Walter Roberson
2025 年 6 月 20 日
At least in R2025a, there is no problem in using "," to concatenate empty datasets, as long as they are empty along either the first or second dimension. (There can be problems if they are empty along the third dimension and the sizes of the first and second dimension do not match the existing data.)
A = zeros(5,3);
B = ones(5,0);
C = zeros(5,2);
D = []; size(D)
E = ones(3,0);
F = ones(0,3);
G = ones(10,9,0);
[A,B,C]
[A,D,C]
[A,E,C]
[A,F,C]
[A,G,C]
4 件のコメント
Walter Roberson
2025 年 6 月 23 日
編集済み: Walter Roberson
2025 年 6 月 23 日
Is the error you recieved due to the fact that you are subscripting an empty array at columns that do not exist?
T1 = randi(9,5,3)
T2 = randi(9,7,4)
T3 = randi(9,4,1)
T4 = randi(9,6,3)
S = @(A,c) A(:,c:c.*(c<=size(A,2)));
%use the auxillary function S to select columns
[S(T1,2); S(T2,2); S(T3,2); S(T4,2)]
%whereas directly indexing might fail
[T1(:,2); T2(:,2); T3(:,2); T4(:,2)]
Walter Roberson
2025 年 6 月 23 日
Huh, there is a difference between cat(1,A,B) and [A;B] ...
A = zeros(5,1);
B = ones(3,0);
[A;B]
cat(1, A, B)
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!