How to use Prod function with cell arrays

조회 수: 14(최근 30일)
Vinay Killamsetty
Vinay Killamsetty 2019년 8월 21일
편집: Adam Danz 2019년 8월 24일
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?

채택된 답변

Adam Danz
Adam Danz 2019년 8월 21일
편집: Adam Danz 2019년 8월 24일
% 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 ];
  댓글 수: 1
Vinay Killamsetty
Vinay Killamsetty 2019년 8월 21일
Thank you very much

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

추가 답변(1개)

Rik
Rik 2019년 8월 21일
편집: Rik 2019년 8월 21일
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
  댓글 수: 1
Vinay Killamsetty
Vinay Killamsetty 2019년 8월 21일
Thank you very much

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

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by