MATLAB Answers

YH
0

how to index a cell array?

Asked by YH
on 13 Nov 2019 at 21:18
Latest activity Commented on by YH
on 18 Nov 2019 at 11:39
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!

  0 Comments

Sign in to comment.

1 Answer

Answer by Shubham Gupta on 14 Nov 2019 at 0:14
 Accepted Answer

Try :
area_r = arrayfun(@(a) cellfun(@(c) trapz(c(c>=0)),a.elevation,'UniformOutput',false), K, 'UniformOutput',false);
I hope it helps !

  3 Comments

YH
on 14 Nov 2019 at 8:43
Thank you for your answer! I think I did not understand exacty what you did, can you please explain to me more what are c and a ? I tried it with my data and I've got the following error: '
Input #2 expected to be a cell array, was double instead'
Shubham Gupta on 14 Nov 2019 at 23:54
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
on 18 Nov 2019 at 11:39
thank you @Shubham Gupta, that was really helpful.

Sign in to comment.