How to remove zeros from an element in a cell array
45 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ebtesam Farid
am 11 Jul. 2021
Kommentiert: Ebtesam Farid
am 12 Jul. 2021
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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 11 Jul. 2021
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 Kommentare
Walter Roberson
am 12 Jul. 2021
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)
Weitere Antworten (1)
dpb
am 11 Jul. 2021
yourarray=cellfun(@(c)c(~-0),yourarray,'UniformOutput',false);
4 Kommentare
dpb
am 12 Jul. 2021
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
am 12 Jul. 2021
Yes, but this is different code; your posted code had c(~-0) not c(c~=0)
Siehe auch
Kategorien
Mehr zu Data Distribution Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!