how to compare cell arrays of different lengths?

조회 수: 6 (최근 30일)
Leonardo Wayne
Leonardo Wayne . 2016년 4월 19일
답변: Sven . 2016년 4월 19일
clc;clear; a=int64(1:3)'; out=num2cell(a) b = int64(1:4)'; out2 =num2cell(b)
index = out == out2;
index doesn't compute because out and out2 are of different lengths. How to make it work?
  댓글 수: 1
Sven 2016년 4월 19일
What would you like the actual answer to be?
For example, the statement
index = out == out2
is definitely not true, so do you want index to return false? Or do you want to know which of the cells in out are equal to their equivalent index in out2?

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

채택된 답변

Sven 2016년 4월 19일
We can start with your input
a = int64(1:3)';
out = num2cell(a);
b = int64(1:4)';
out2 =num2cell(b);
We will presume you're looking for something that tells you that "the contents of indexes 1, 2, and 3 match between the two cells", so you're looking for index to return the values 1, 2, and 3.
You have a 3-length and a 4-length cell array. By definition the 4th cell element can't match anything, so we only need to consider up to the smallest array length.
minLen = min(length(out),length(out2));
We can then use cellfun() to compare each pair of elements:
index = find(cellfun(@isequal, out(1:minLen), out2(1:minLen)))
Note that you didn't necessarily need to put integers into cells to do this. Perhaps your real data contains strings or other non-numeric contents, but if you're working with arrays originally you can do the same thing with the raw array contents:
index = find(arrayfun(@isequal, a(1:minLen), b(1:minLen)))
Did this help you out?
Thanks, Sven

추가 답변 (0개)


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