Apply function to two cell arrays element-wise

조회 수: 18 (최근 30일)
dandan
dandan 2018년 2월 2일
댓글: dandan 2018년 2월 5일
I have two cell arrays, xdata and CDF. I want to apply kstest element-wise to each pair of xdata and CDF cells (e.g., xdata{1} and CDF{1}, xdata{2} and CDF{2}, etc.).
Each cell of xdata is nx1 (data sample values), and each cell of CDF ix nx2 (theoretical [x,CDF] values).
I can do this with a for loop:
for i=1:length(xdata)
[h{i},p{i},ks2stat{i}]=kstest(xdata{i},CDF{i});
end
But I'm wondering if there's a clever way to do it more cleanly with anonymous functions and cellfun? Something along the lines of:
[h,p,ks2stat]=deal(cellfun(@(xc) kstest(xc(:,1),xc(:,2:3)),{[xdata CDF]},'Uniform',0));
Any ideas would be appreciated. Thanks!

채택된 답변

Guillaume
Guillaume 2018년 2월 2일
You're overcomplicating:
[h, p, k2stat] = cellfun(@kstest, xdata, CDF, 'UniformOutput', false);
  댓글 수: 3
Guillaume
Guillaume 2018년 2월 5일
편집: Guillaume 2018년 2월 5일
"I have two cell arrays, xdata and CDF"
input #2 expected to be a cell array, was double instead
One of these statement contradicts the other.
Putting brackets around the inputs is very unlikely to be the correct fix. It would only work if both xdata and CDF were matrices, not cell array and would then be simply equivalent to:
[h, p, k2stat] = ktest(xdata, CDF);
h = {h}; p = {p}; k2stat = {k2stat}; %useless stuffing of the results in cell arrays
And if xdata and CDF were really structures then your code would certainly error. Be careful with the terms you use. cell arrays, matrices, structures, tables (another term often misused) are very different types.
dandan
dandan 2018년 2월 5일
Oops, sorry, you're right. I was simplifying the problem to explain it here and forgot I was referencing structures in the real version. You're correct, the way you originally wrote it does work if xdata and CDF are cell arrays. Thank you and sorry for the confusion!

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

추가 답변 (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