How to extract element of all matrices within a cell array using cellfun?

I need to extract (2,1) i.e. second row and first column element of all matrices within cell array ?

 채택된 답변

Are all the matrices in the cells the same size? If so, just use cell2mat() and indexing:
[rows, columns] = size(ca{1})
m = cell2mat(ca)
m21 = m(2:rows:end, 1:columns:end)

댓글 수: 5

When i ran this , i get error , this possibly due to Nan , how to account for them first
m = cell2mat(CORCOEF)
Error using cat
Dimensions of matrices being concatenated are not consistent.
Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});
All matrices in your cells are not the same size. Some are a different size than the others.
Thanks sir , I got it:)
Of course, you could always use a simple for loop:
output = ones(1, numel(ca));
for k = 1 : numel(ca)
thisCellsContents = ca{k}; % Extract this one particular cell
output(k) = thisCellsContents(2, 1);
end
Thanks sir, I figured it out.

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

추가 답변 (2개)

This looks like homework to me. Here is a big hint:
Create a function that extracts this for you and use cellfun to apply it to all cells ...
MyFun = @(M) M(...)

댓글 수: 5

MyFun = @(M) M(2,1)
A(idx) = cellfun(MyFun,C(idx));
C is my cell array having matrices and in some matrices i have Nan too
When i run above code i get
Index exceeds matrix dimensions.
Error in @(M)M(2,1)
I have Nan values too in matrix , how to get them ?
The error indicates that some of your matrices do not have a (2,1) element. So you will need to deal with that. Is this not expected? I.e., are all of your matrices supposed to have a (2,1) element? If not, then what do you want for a result?
I have checked all elements have 2,1 elements but only a few have Nan in them , so i will not consider those matrices. But how to get 2,1 element from all matrices with some having Nan?
The value of the (2,1) element makes no differrence to indexing ... whether it is finite or inf or NaN. You will not get an "index exceeds" error just because the element is NaN. You get the error because there is no (2,1) element. You need to re-check your matrices. What do you get when you run this:
C = your cell array of matrices
min(cellfun(@numel,C))
min(cellfun(@(c)size(c,1),C))
Thanks sir , i got it :)

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

Ali Nik
Ali Nik 2023년 4월 16일

0 개 추천

Hi I want to use all nested arrays inside each cell. Thank you for your help His photo is attached.

댓글 수: 1

Not sure how this is an answer to @NS. And when you said "His photo is attached", we're not sure what photo you're talking about or where it is. Certainly NS's photo is not attached to your Answer.
If you have your own question, start a new question and attach your cell array in a .mat file after you read this:

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

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

질문:

NS
2018년 12월 6일

댓글:

2023년 4월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by