Assign a value to each page of a 3D Matrix

조회 수: 25 (최근 30일)
DS
DS 2022년 1월 11일
댓글: Stephen23 2022년 1월 11일
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

채택된 답변

Bjorn Gustavsson
Bjorn Gustavsson 2022년 1월 11일
편집: Bjorn Gustavsson 2022년 1월 11일
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
Bjorn Gustavsson
Bjorn Gustavsson 2022년 1월 11일
My pleasure.
Stephen23
Stephen23 2022년 1월 11일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by