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일

1 개 추천

% 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개)

Rik
Rik 2019년 8월 21일
편집: Rik 2019년 8월 21일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

제품

릴리스

R2019a

질문:

2019년 8월 21일

편집:

2019년 8월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by