Azzera filtri
Azzera filtri

Searching in cell arrays.

1 visualizzazione (ultimi 30 giorni)
lucksBi
lucksBi il 5 Apr 2017
Commentato: lucksBi il 6 Apr 2017
hi i have 2 cell arrays:
array1={6x6 double;6x6 double} & its elements are:
array1{1,1}=[0,0,0,0,0,0;0,0,0,0,0,0;0,2,0,0,0,0;1,2,3,4,0,0;0,0,0,0,0,0;0,0,0,0,0,0]
array1{2,1}=[0,0,3,4,0,0;1,0,3,4,0,0;0,2,0,0,0,0;1,2,3,4,0,0;0,0,0,0,0,0;0,0,0,0,0,0]
second cell array is:
array2={{[3;4]};[1;2;3;4]}
i want to search all elements of array2 (one by one) in corresponding cell of array1 and if found replace it with its row index.
Thanks in advance.
  2 Commenti
Rik
Rik il 5 Apr 2017
I don't understand what exactly it is that you want to do. One part of that is that code is not readable. Use the {}Code button.
What do you expect the outcome to be?

Accedi per commentare.

Risposta accettata

Guillaume
Guillaume il 5 Apr 2017
Modificato: Guillaume il 5 Apr 2017
I'm not entirely sure of the output you want. Maybe:
function rows = findrow(matrix, value)
%find the rows of matrix where value is found
[rows, ~] = find(matrix == value);
rows = unique(rows);
end
Used with your cell arrays:
array1 = {[0,0,0,0,0,0;0,0,0,0,0,0;0,2,0,0,0,0;1,2,3,4,0,0;0,0,0,0,0,0;0,0,0,0,0,0];
[0,0,3,4,0,0;1,0,3,4,0,0;0,2,0,0,0,0;1,2,3,4,0,0;0,0,0,0,0,0;0,0,0,0,0,0]};
array2 = {[3;4]; [1;2;3;4]}; %I assume the cell array within cell array was a typo
out = cellfun(@(m, v) arrayfun(@(v) findrow(m, v), v, 'UniformOutput', false), ...
array1, ...
array2, ...
'UniformOutput', false)
  3 Commenti
Guillaume
Guillaume il 5 Apr 2017
Right, I'd made two typos on the cellfun line. Fixed now.
lucksBi
lucksBi il 6 Apr 2017
Thank you so much for this very optimal piece of code.

Accedi per commentare.

Più risposte (1)

Andrei Bobrov
Andrei Bobrov il 6 Apr 2017
another variant
m - file:
function out = findrows(a,b)
[~,ii] = ismember(a,b);
[i1,~] = find(ii);
out = accumarray(ii(ii > 0),i1,[],@(x){unique(x)});
end
using:
out = cellfun(@(x,y)findrows(x,y),array1,array2,'un',0);

Community Treasure Hunt

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

Start Hunting!

Translated by