MATLAB Answers

Add element to the matrix in one sentence

조회 수: 2(최근 30일)
Xin
Xin 14 Jun 2017
편집: Andrei Bobrov 14 Jun 2017
I have a 2D matrix, say A=zeros(10,10). I want to add a vector of number to the matrix. I have the index of the elements, but it is repeated. E.g. the index [5,3,2,5,3,100,5] and the value is some random [1,2,3,4,5,6,7]. I then want to add 1 into 5th element of A, 2 into 3rd element and so on. How do I do this in one line?

  댓글 수: 4

표시 이전 댓글 수: 1
Xin
Xin 14 Jun 2017
Because I want to vectorize the whole code. Eventually A matrix is 1e7*1e7 and it is very slow if you do it in a loop
Adam
Adam 14 Jun 2017
You can vectorize multi-line statements too.
Xin
Xin 14 Jun 2017
Could you please be more specific. That's what I have been doing but for this problem it is not very straightforward.

로그인 to comment.

채택된 답변

Andrei Bobrov
Andrei Bobrov 14 Jun 2017
편집: Andrei Bobrov 14 Jun 2017
A=zeros(10,10);
ii = [5,3,2,5,3,100,5];
var = 1:7;
[ii,ib] = unique(ii);
A(ii) = var(ib);
or
A([5,3,2,5,3,100,5]) = 1:7

  댓글 수: 3

Xin
Xin 14 Jun 2017
The only problem is that if you do that, you only save the last entry into A. That means A(1)=7 but I want to add 1 and 7 into A(1)
Andrei Bobrov
Andrei Bobrov 14 Jun 2017
This is not possible for a double array if only for cell array.
Andrei Bobrov
Andrei Bobrov 14 Jun 2017
ii = [5,3,2,5,3,100,5];
var = 1:7;
A = reshape(accumarray(ii(:),var(:),[100 1],@(x){x(:)'}),10,[]);

로그인 to comment.

추가 답변(1개)

Guillaume
Guillaume 14 Jun 2017
편집: Guillaume 14 Jun 2017
If I understood correctly
A = zeros(10,10);
indices = [5,3,2,5,3,100,5];
values = [1,2,3,4,5,6,7];
A = A + reshape(accumarray(indices(:), values(:), [numel(A), 1]), size(A))
would be one way to do it. Alternatively,
[uindices, ~, loc] = unique(indices);
sumvalues = accumarray(loc(:), values(:));
A(uindices) = A(uindices) + sumvalues;

  댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.