Matlab: vectorization of index value assignment in a matrix

Sorry in advance if this question is a duplicate, or if the solution to this question is very straight forward in Matlab. I have an M x N matrix A, a 1 x M indvector, and another vector val. For example,

A = zeros(6,5);
ind = [3 4 2 4 2 3];
val = [1 2 3];

I would like to quote the following code:

for i = 1 : size(A,1)
    A(i, ind(i)-1 : ind(i)+1) = val;
end

>> A

A =

 0     1     2     3     0
 0     0     1     2     3
 1     2     3     0     0
 0     0     1     2     3
 1     2     3     0     0
 0     1     2     3     0

That is, for the line I from, AI want to insert a vector valin a specific place, as indicated in the i-th record ind. What is the best way to do this in Matlab without a for loop?

+4
source share
2 answers

, bsxfun : , , , . (- Matlab) .

A, .

-1 ind. , .

%// Data
ind = [3 4 2 4 2 3]; %// indices
val = [1 2 3]; %// values
d = -1; %// displacement for indices. -1 in your example

%// Let go
n = numel(val);
m = numel(ind);
N = max(ind-1) + n + d;  %// number of rows in A (rows before transposition)
mask = bsxfun(@ge, (1:N).', ind+d) & bsxfun(@le, (1:N).', ind+n-1+d); %// build mask
A = zeros(size(mask)); %/// define A with zeros
A(mask) = repmat(val(:), m, 1); %// fill in values as indicated by mask
A = A.'; %// transpose

:

A =
     0     1     2     3     0
     0     0     1     2     3
     1     2     3     0     0
     0     0     1     2     3
     1     2     3     0     0
     0     1     2     3     0

d = 0 ( ):

A =
     0     0     1     2     3     0
     0     0     0     1     2     3
     0     1     2     3     0     0
     0     0     0     1     2     3
     0     1     2     3     0     0
     0     0     1     2     3     0
+3

bsxfun , bsxfun's -

N = numel(ind);
A(bsxfun(@plus,N*[-1:1]',(ind-1)*N + [1:N])) = repmat(val(:),1,N)

-

>> ind
ind =
     3     4     2     4     2     3
>> val
val =
     1     2     3
>> A = zeros(6,5);
>> N = numel(ind);
>> A(bsxfun(@plus,N*[-1:1]',(ind-1)*N + [1:N])) = repmat(val(:),1,N)
A =
     0     1     2     3     0
     0     0     1     2     3
     1     2     3     0     0
     0     0     1     2     3
     1     2     3     0     0
     0     1     2     3     0
+1

Source: https://habr.com/ru/post/1605643/


All Articles