Assign a value to each page of a 3D Matrix

20 Ansichten (letzte 30 Tage)
DS
DS am 11 Jan. 2022
Kommentiert: Stephen23 am 11 Jan. 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

Akzeptierte Antwort

Bjorn Gustavsson
Bjorn Gustavsson am 11 Jan. 2022
Bearbeitet: Bjorn Gustavsson am 11 Jan. 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 Kommentare
Bjorn Gustavsson
Bjorn Gustavsson am 11 Jan. 2022
My pleasure.
Stephen23
Stephen23 am 11 Jan. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by