Multiplying two double arrays within a structure

8 views (last 30 days)
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 Comment
James Tursa
James Tursa on 15 Aug 2019
Edited: James Tursa on 15 Aug 2019
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.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 16 Aug 2019
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{:});

More Answers (0)

Community Treasure Hunt

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

Start Hunting!