Assign a value to each page of a 3D Matrix

28 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Bjorn Gustavsson
Bjorn Gustavsson il 11 Gen 2022
Modificato: Bjorn Gustavsson il 11 Gen 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 Commenti
Stephen23
Stephen23 il 11 Gen 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by