Multiplying two double arrays within a structure
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Kelly
el 15 de Ag. de 2019
Respondida: Guillaume
el 16 de Ag. de 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 comentario
James Tursa
el 15 de Ag. de 2019
Editada: James Tursa
el 15 de Ag. de 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.
Respuesta aceptada
Guillaume
el 16 de Ag. de 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{:});
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!