Filter löschen
Filter löschen

Searching in cell arrays.

1 Ansicht (letzte 30 Tage)
lucksBi
lucksBi am 5 Apr. 2017
Kommentiert: lucksBi am 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 Kommentare
Rik
Rik am 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?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Andrei Bobrov
Andrei Bobrov am 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);

Kategorien

Mehr zu Matrix Indexing 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!

Translated by