I have a 1D array (365x1) that I need to reshape into a 3D array (365x1x1) to divide into 3D array (365x721x1440). What's the most efficient means of accomplishing this task?

 Respuesta aceptada

the cyclist
the cyclist el 5 de Ag. de 2023
MATLAB arrays implicitly have length-1 dimensions after the defined dimensions. For example
% Define 365x1 array
M = rand(365,1);
% Length in 3rd dimension
size(M,3)
ans = 1
% Length in 31st dimension
size(M,31)
ans = 1
Regarding how that ends up being (365x721x1440), you'll need to provide more detail.

4 comentarios

John Cruce
John Cruce el 5 de Ag. de 2023
Let me try again.
A=rand(365,721,1440);
B=[1:365]'
I want to divide A by B along the first dimension (365). My thought was that I'll need to reshape B then divide the two. Does that sound right?
Torsten
Torsten el 5 de Ag. de 2023
You mean
A=rand(365,721,1440);
B=[1:365]';
for i = 1:365
A(i,:,:) = A(i,:,:)/B(i);
end
A
?
DGM
DGM el 6 de Ag. de 2023
Editada: DGM el 6 de Ag. de 2023
I think we're getting confused by the suggestion of "reshaping". The way it appears to me, reshaping A is not necessary. It appears as this is simply a misunderstanding how to make array sizes compatible for arithmetic operations. Consider the example:
A = (1:4).' % a column vector
A = 4×1
1 2 3 4
B = 2*ones(4,4,2) % a 3D array with the same page height
B =
B(:,:,1) = 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 B(:,:,2) = 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
% you could expand A to have the same size as B
% A = repmat(A,[1 4 2]);
% but it's not necessary
A./B
ans =
ans(:,:,1) = 0.5000 0.5000 0.5000 0.5000 1.0000 1.0000 1.0000 1.0000 1.5000 1.5000 1.5000 1.5000 2.0000 2.0000 2.0000 2.0000 ans(:,:,2) = 0.5000 0.5000 0.5000 0.5000 1.0000 1.0000 1.0000 1.0000 1.5000 1.5000 1.5000 1.5000 2.0000 2.0000 2.0000 2.0000
So long as the arrays are compatibly-sized along their non-singleton dimensions, you should be able to perform elementwise arithmetic without explicitly expansion. If you were running a version older than R2016b, the recommended method would be to use bsxfun() instead of repmat().
Of course, I might be interpreting the question wrong.
John Cruce
John Cruce el 6 de Ag. de 2023
You're excatly right. I was definitely overcomplicating it.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Productos

Versión

R2023a

Preguntada:

el 5 de Ag. de 2023

Comentada:

el 6 de Ag. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by