How to remove zeros from an element in a cell array
45 ビュー (過去 30 日間)
古いコメントを表示
Hi all,
I have two cell arrays each contain 12 cells, each cell contains different matrix size (31,1) or (30,1) or (28,1), each cell in the array contains a bunch of zeros, and I need to remove these zeros, because it indicates that there is no data at this day
here are an example of my data,
A = {[1 0 1], [2 0 2], ......., [12 0 12]}
B = {[0 2 1], [1 2 0], ........, [12 0 12]}
my purpose is to compare A with B, and to do that I have to remove the zeros and the coincident index in the other cell
A(1,1){2} and B(1,1){2} = []; aslo A(1,1){1} and B(1,1){1}=[];
any suggestions, please??
0 件のコメント
採用された回答
Walter Roberson
2021 年 7 月 11 日
monthlengths = [28 30 31];
C = arrayfun(@(x) randi([0 9], 1, monthlengths(randi(3))), 1:12, 'uniform', 0)
reduced_C = cellfun(@(c) c(c~=0), C, 'uniform', 0)
4 件のコメント
Walter Roberson
2021 年 7 月 12 日
Well, if you really want... but I do not see what advantages that would have over the code I already posted using masks to select elements. The setdiff(1:end,m) to remove the zero elements whose index you know is pretty clumsy: easier to use logical variables, which you can use to index or use the negation to index.
monthlengths = [28 30 31];
A = arrayfun(@(x) randi([0 9], 1, monthlengths(randi(3))), 1:12, 'uniform', 0)
B = cellfun(@(c) randi([0 9], 1, length(c)), A, 'uniform', 0)
z_A = cellfun(@(c) find(c==0), A, 'uniform', 0);
z_B = cellfun(@(c) find(c==0), B, 'uniform', 0);
z = cellfun(@(zA, zB) union(zA, zB), z_A, z_B, 'uniform', 0)
reduced_A = cellfun(@(C, m) C(setdiff(1:end,m)), A, z, 'uniform', 0)
reduced_B = cellfun(@(C,m) C(setdiff(1:end,m)), B, z, 'uniform', 0)
その他の回答 (1 件)
dpb
2021 年 7 月 11 日
yourarray=cellfun(@(c)c(~-0),yourarray,'UniformOutput',false);
4 件のコメント
dpb
2021 年 7 月 12 日
Au contraire --
>> c{:}
ans =
5
3
1
3
0
ans =
2
5
2
1
1
>>
>> c=cellfun(@(c)c(c~=0),c,'UniformOutput',false)
c =
1×2 cell array
{4×1 double} {5×1 double}
>> c{:}
ans =
5
3
1
3
ans =
2
5
2
1
1
>>
Walter Roberson
2021 年 7 月 12 日
Yes, but this is different code; your posted code had c(~-0) not c(c~=0)
参考
カテゴリ
Help Center および File Exchange で Data Distribution Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!