Effacer les filtres
Effacer les filtres

Searching in cell arrays.

1 vue (au cours des 30 derniers jours)
lucksBi
lucksBi le 5 Avr 2017
Commenté : lucksBi le 6 Avr 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 commentaires
Rik
Rik le 5 Avr 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?

Connectez-vous pour commenter.

Réponse acceptée

Guillaume
Guillaume le 5 Avr 2017
Modifié(e) : Guillaume le 5 Avr 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 commentaires
Guillaume
Guillaume le 5 Avr 2017
Right, I'd made two typos on the cellfun line. Fixed now.
lucksBi
lucksBi le 6 Avr 2017
Thank you so much for this very optimal piece of code.

Connectez-vous pour commenter.

Plus de réponses (1)

Andrei Bobrov
Andrei Bobrov le 6 Avr 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);
  1 commentaire
lucksBi
lucksBi le 6 Avr 2017
Good one.. thanks alot.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by