Editing multiple elements of an array in one line

조회 수: 19 (최근 30일)
Kyle Ruzic
Kyle Ruzic 2018년 5월 16일
댓글: Rik 2018년 5월 16일
My problem is this, I have a huge array and I want to edit multiple elements of the same array that I know the location of. Here's how I would assume this should work based on how matlab handles arrays
h = zeros(10,10,10,2); % just a simple example array
b = [10 5]; % elements I want to place in new location
i = [1 2]; % "locations" I want to place them in
h = h(1,1,1,i) + b(i)
Now what I would expect is for h(1,1,1,1) = 10 and h(1,1,1,2) = 5. But instead what you get is h(1,1,1,1) = [10 5] and h(1,1,1,2) = [10 5]
Why is this? I know a solution is to simple edit them in a loop, however this isn't actually answering the problem.
Thanks

채택된 답변

Rik
Rik 2018년 5월 16일
The error you get for your example will probably depend the release. On R2018a, the implicit expansion tries to expand b to fit the 4D selection from h. What I needed to do is make sure that b is 1x1x1x(numel(b)):
h = zeros(10,10,10,2); % just a simple example array
b = [10 5]; % elements I want to place in new location
i = [1 2]; % "locations" I want to place them in
h(1,1,1,i) = h(1,1,1,i) + permute(b(:),numel(size(h)):-1:1);
h(1,1,1,1)
h(1,1,1,2)
  댓글 수: 2
Kyle Ruzic
Kyle Ruzic 2018년 5월 16일
Sorry I edited the question as you were typing your answer to change h(1,1,1,i) to just h, which is what I was doing to produce the result I mentioned in the question.
I'm a bit confused by how this
permute(b(:),numel(size(h)):-1:1);
is changing the size of b.
Thanks for the quick response!
Rik
Rik 2018년 5월 16일
If you read the doc for permute, you can see that it changes the order of the dimensions, so in this case, the 2x1 vector resulting from the b(:) operation, is changed. A 2x1 vector is the same as a 2x1x1x1 array, so permute uses the vector [4 3 2 1] (the output of numel(size(h)):-1:1)) to change this to 1x1x1x2, which fits the excerpt from h defined by the h(1,1,1,i) operation.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by