Multiplying two double arrays within a structure

11 次查看(过去 30 天)
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 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by