Multiplying two double arrays within a structure

14 vues (au cours des 30 derniers jours)
Kelly
Kelly le 15 Août 2019
Réponse apportée : Guillaume le 16 Août 2019
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 commentaire
James Tursa
James Tursa le 15 Août 2019
Modifié(e) : James Tursa le 15 Août 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.

Connectez-vous pour commenter.

Réponse acceptée

Guillaume
Guillaume le 16 Août 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{:});

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by