Multiplying two double arrays within a structure

조회 수: 13 (최근 30일)
Kelly
Kelly 2019년 8월 15일
답변: Guillaume 2019년 8월 16일
Hi,
I am trying to multiply two arrays together, which are contained in the same structure. I have a 1x28 structure containing different variables all a double array (7974x1) and I need to multiply together two of these variables within each structure.
My code:
% SerStruct (1x28 struct)
% A (7974x1 double)
% B (7974x1 double)
for i = 1:length(SerStruct);
dat1 = SerStruct(i).A.* SerStruct(i).B;
end
The answer I get is: dat1 = 88016x1
However if I count the number of rows in each double array (either A or B) within each 28 cells, there should be more like 500000x1.
Can anyone please help me?
Thank you!
  댓글 수: 1
James Tursa
James Tursa 2019년 8월 15일
편집: James Tursa 2019년 8월 15일
What is size(SerStruct(i).A) and size(SerStruct(i).B) for each i? This should be pretty simple to debug and figure out what is going on by just examining the sizes.

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

채택된 답변

Guillaume
Guillaume 2019년 8월 16일
It sounds like you want to vertically concatenate the result of the multiplication for each element of your structure array.
With a loop:
result = cell(size(SerStruct)); %preallocate temporary cell array to store the result of the multiplications
for idx = 1:numel(SerStruct) %iterate over each element of the structure array (with fields A and B
result{idx} = SerStruct(idx).A .* SerStruct(idx).B; %do the multiplication for each element
end
result = vertcat(result{:}); %vertically concatenate the whole lot (could also use cell2mat if the structure array is a column vector
With arrayfun:
result = arrayfun(@(s) s.A .* s.B, SerStruct, 'UniformOutput', false); %does the same thing as the loop
result = vertcat(result{:});

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by