How to remove zeros from an element in a cell array
42 次查看(过去 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)
另请参阅
类别
在 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!