how to index a cell array?

조회 수: 3 (최근 30일)
YH
YH 2019년 11월 13일
댓글: YH 2019년 11월 18일
Hallo,
I have a structure (K) with many fields, containg a field (elevation) which is (161*1 cell) array, each cell is a matrix (n*1) double.
I wanted to find all the elements in each matrix that is more than 0 then calculate the area of these values (above 0)
firstly I made a new cell array of the indexs that I needed
idx = arrayfun(@(K) K.elevation >=0, K, 'UniformOutput', false)';
now I want to use the function trapz to find the area
I tried many things, but I'm getting always errors like 'Unable to use a value of type cell as an index or 'Expected one output from a curly brace or dot indexing expression, but there were 161 results'
Can someone help me with this issue?
many thanks!

채택된 답변

Shubham Gupta
Shubham Gupta 2019년 11월 14일
Try :
area_r = arrayfun(@(a) cellfun(@(c) trapz(c(c>=0)),a.elevation,'UniformOutput',false), K, 'UniformOutput',false);
I hope it helps !
  댓글 수: 3
Shubham Gupta
Shubham Gupta 2019년 11월 14일
편집: Shubham Gupta 2019년 11월 15일
Above code is same as:
for i = 1:length(K)
elevation_cell = K(i).elevation;
for j = 1:size(elevation_cell,1)
mat_in_cell = elevation_cell{j};
mat_conditional = mat_in_cell(mat_in_cell>0);
area_r{i}{j} = trapz(mat_conditional);
end
end
So in the above code, 2nd loop is replaced by
area_r = cellfun(@(c) trapz(c(c>=0)),elevation_cell,'UniformOutput',false);
Here c is the variable which is changing according to the index of the elevation_cell.
Finally, if the length(K) > 1 then we can execute above line for each element of K without using the for loop, using arrayfun().
So here a is basically the element of K structure which change accoding to the loop. Hence the above code:
area_r = arrayfun(@(a) cellfun(@(c) trapz(c(c>=0)),a.elevation,'UniformOutput',false), K, 'UniformOutput',false);
I will post a simple example for which the posted code is working for me, let me know where is your data different from this example?
K(1).elevation = {[1;2;3;9];[3;-4;5;-2];[-1;2;4;3]};
K(2).elevation = {[-1;4;-2;7];[-2;-3;10;7];[1;4;-2;-4]};
As, you can see K is 2x1 structure with elevation containing 3x1 cell and each cell has 4x1 double. Now, if run the above code it gives me output:
area_r =
{3x1 cell} {3x1 cell}
Where 1st & 2nd columns are area cell corresponding to K(1) & K(2) respectively. And each cell area_r{1} is the area corresponding to the cell number of K.elevation.
YH
YH 2019년 11월 18일
thank you @Shubham Gupta, that was really helpful.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by