how to index a cell array?
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Shubham Gupta
il 14 Nov 2019
Try :
area_r = arrayfun(@(a) cellfun(@(c) trapz(c(c>=0)),a.elevation,'UniformOutput',false), K, 'UniformOutput',false);
I hope it helps !
3 Commenti
Shubham Gupta
il 14 Nov 2019
Modificato: Shubham Gupta
il 15 Nov 2019
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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!