How to use Prod function with cell arrays

8 vues (au cours des 30 derniers jours)
Vinay Killamsetty
Vinay Killamsetty le 21 Août 2019
Modifié(e) : Adam Danz le 24 Août 2019
I have defined a cell array in the name of "T_mn" having "n_layers" number of cells.
Each cell is having a vector containing "n_modes" elements.
I want to find the product of element "req_mode" in each vector among the cells between "wire_lay" - "obs_lay"
when I though of using this code it is not working
for wire_lay=1:1:n_layers
for req_mode=1:1:l_modes
for obs_lay=1:1:n_layers
A=prod(T_mn{wire_lay:1:obs_lay}(req_mode))
end
end
end
Can you help?

Réponse acceptée

Adam Danz
Adam Danz le 21 Août 2019
Modifié(e) : Adam Danz le 24 Août 2019
% Extract the value in index "req_mode" from each cell in "T_mn"
% starting and ending at cell index "wire_lay" and "obs_lay" respectively.
wire_lay = 2;
obs_lay = 4;
req_mode = 3;
vec = cellfun(@(x)x(req_mode),T_mn(wire_lay:obs_lay));
prd = prod(vec);
% DEMO data
T_mn{1} = [1 2 3 4];
T_mn{2} = [5 6 7 8];
T_mn{3} = [9 10 11 12];
T_mn{4} = [13 14 15 16];
T_mn{5} = [0 0 0 0 ];

Plus de réponses (1)

Rik
Rik le 21 Août 2019
Modifié(e) : Rik le 21 Août 2019
It is always good to consider if the task you want to accomplish asks for a different data design. I think it is much easier to do what you want (and optimize by removing the loops) if you first convert your cell array to doubles.
Note that with this order of loops and this data design, you can replace the req_mode loop by specifying the dimension in your call to prod (A=prod(T(:,wire_lay:obs_lay),2)).
Also, the cumprod function could be helpful in optimizing this code.
% DEMO data
T_mn{1} = [1 2 3 4];
T_mn{2} = [5 6 7 8];
T_mn{3} = [9 10 11 12];
T_mn{4} = [13 14 15 16];
T_mn{5} = [0 0 0 0 ];
n_layers=5;
n_modes=4;
T=squeeze(cat(3,T_mn{:}));
%cell2mat also works, but only if T_mn is 1-by-n and T_mn{} is m-by-1
for wire_lay=1:n_layers
for req_mode=1:n_modes
for obs_lay=wire_lay:n_layers
A=prod(T(req_mode,wire_lay:obs_lay));
%do something with A, otherwise it will get overwritten
end
end
end

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by