Borrar filtros
Borrar filtros

Searching in cell arrays.

1 visualización (últimos 30 días)
lucksBi
lucksBi el 5 de Abr. de 2017
Comentada: lucksBi el 6 de Abr. de 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 comentarios
Rik
Rik el 5 de Abr. de 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?

Iniciar sesión para comentar.

Respuesta aceptada

Guillaume
Guillaume el 5 de Abr. de 2017
Editada: Guillaume el 5 de Abr. de 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 comentarios
Guillaume
Guillaume el 5 de Abr. de 2017
Right, I'd made two typos on the cellfun line. Fixed now.
lucksBi
lucksBi el 6 de Abr. de 2017
Thank you so much for this very optimal piece of code.

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 6 de Abr. de 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 comentario
lucksBi
lucksBi el 6 de Abr. de 2017
Good one.. thanks alot.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by