简体   繁体   中英

Matlab: How to insert zeros in specific places of vector

Can someone help me with the following problem in Matlab? I have a first vector containing the elements values. For example,

[2 8 4 9 3]. 

And a second one with the desired places in a second vector. For example,

[0 0 1 0 0 0 0 1 1 0 0 1 0 0 1]. 

Now I want to put the values from the first vector on the positions of the second one to end up with

[0 0 2 0 0 0 0 8 4 0 0 9 0 0 3]. 

What is the most efficient way of doing this when the size of the vector can be very large. (then thousands of elements)?

You can consider the y values as logical indicators, then use logical indexing to set those values to the values in x.

x = [2 8 4 9 3];
y =  [0 0 1 0 0 0 0 1 1 0 0 1 0 0 1];
y(logical(y)) = x;

Alternatively, you could use

y(y==1) = x;

Use self-indexing:

% Your values:
V = [2 8 4 9 3];

% The desired locations of these values:
inds = [0 0 1 0 0 0 0 1 1 0 0 1 0 0 1];

% index the indices and assign
inds(inds>0) = V

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM