Assign a value to each page of a 3D Matrix

25 views (last 30 days)
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

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 11 Jan 2022
Edited: Bjorn Gustavsson on 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 Comments
Stephen23
Stephen23 on 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!