hello,
i have cell matrix size(1*1000) each element is matrix (10*10)
i want to test if matrix is an element of cell or not how to do it?

1 commentaire

amina KHARBACHE
amina KHARBACHE le 6 Juil 2017
i was lloking for simple insttruction with matlab who find directly the matrix inside the cell matrix
but with a simple loop for can do it
for i=1numel(cellmatrix) if cellmatrix{1,i}==test_matrix save_index=i; break end end
thanx in advance ^^

Connectez-vous pour commenter.

 Réponse acceptée

Jan
Jan le 6 Juil 2017
Modifié(e) : Jan le 6 Juil 2017

1 vote

index = [];
for k = 1:numel(C)
if iseuqal(C{k}, test_matrix)
index = k;
break;
end
end
Or if you need all occurrences:
index = false(1, numel(C));
for k = 1:numel(C)
if isequal(C{k}, test_matrix)
index(k) = true;
end
end
found = find(index); % Or use the logical index vector directly
A shorter form:
found = find(cellfun(@(c) isequal(c, test_matrix), C));
At least under R2009a, the for loop method is 6 times faster for finding a 10x10 matrix in a 1 x 1000 cell array. cellfun is nice, but slow.

2 commentaires

amina KHARBACHE
amina KHARBACHE le 6 Juil 2017
i was lloking for simple insttruction with matlab who find directly the matrix inside the cell matrix
but with a simple loop for can do it
for i=1numel(cellmatrix) if cellmatrix{1,i}==test_matrix save_index=i; break end end
thanx in advance ^^
*************************
i already found it with loop for
thank you so much ^^
Jan
Jan le 6 Juil 2017
Modifié(e) : Jan le 6 Juil 2017
Do not use == for the comparison, because it works elementwise. It returns a matrix with TRUE for all equal elements, but Matlab's IF expects a scalar. Therefore internally this is evaluated:
if (all(cellmatrix{1,i}(:) == test_matrix(:)) && ~isempy(cellmatrix{1.i})
Better use isequal as in the code I've posted to avoid any ambiguities.
Note: To my surprise this seems to be slightly slower:
index = false(1, numel(C));
for k = 1:numel(C)
index(k) = isequal(C{k}, X);
end
m = find(index);

Connectez-vous pour commenter.

Plus de réponses (1)

Rik
Rik le 6 Juil 2017

0 votes

Have you tried ismember?

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by