Assign a value to each page of a 3D Matrix

30 visualizaciones (últimos 30 días)
DS
DS el 11 de En. de 2022
Comentada: Stephen23 el 11 de En. de 2022
Hello everyone
I got a 3D Matrix:
A=ones[3,3,3]
and a Vector of values:
x=[10 20 30]
How can I assign the values of x to all values of a whole page of A?
My goal is to get A to be:
A( :, :, 1) = 10
A( :, :, 2) = 20
A( :, :, 3) = 30
I want it to be vectorised - also the number of elements of x (and the number of pages in A - respectively) can change in my program)
Can anyone help? Much appreciated!
Best Regard
DS

Respuesta aceptada

Bjorn Gustavsson
Bjorn Gustavsson el 11 de En. de 2022
Editada: Bjorn Gustavsson el 11 de En. de 2022
If we stick to the first rule of programming (KISS) this should get the job done:
A = zeros([3,4,5]);
x = [10 20 30 2^.5 exp(1)];
for i1 = 1:numel(x),
A(:,:,i1) = x(i1);
end
Unless you have very specific needs I see no reason to mess about with anything else - unless you can present profiling-results showing that this is a time-critical step in a program...
HTH
  6 comentarios
Bjorn Gustavsson
Bjorn Gustavsson el 11 de En. de 2022
My pleasure.
Stephen23
Stephen23 el 11 de En. de 2022
While vectorization of this might be possible with some effort, it would be more complex, obfuscated, and require large intermediate arrays (i.e. be slow). This answer is perfectly good MATLAB code, whatever your supervisor might think.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by