필터 지우기
필터 지우기

Searching in cell arrays.

조회 수: 1 (최근 30일)
lucksBi
lucksBi 2017년 4월 5일
댓글: lucksBi 2017년 4월 6일
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
Rik
Rik 2017년 4월 5일
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?

댓글을 달려면 로그인하십시오.

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2017년 4월 6일
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
lucksBi
lucksBi 2017년 4월 6일
Good one.. thanks alot.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by