How can I match these vector values?

1 次查看(过去 30 天)
Robert
Robert 2014-12-11
I have 2 vectors. One is 1505 values long with 200 1s spread throughout and the rest NaNs. The other is only 200 values long. I want to space out the 200 value long vector so that those 200 values match the position of the 1s in the 1505 long vector as they represent where the data should be positioned.
I am a matlab newbie so as much detail as possible would be appreciated.
Thanks in advance for any help!
  1 个评论
John D'Errico
John D'Errico 2014-12-11
It is time for you to learn the basics of MATLAB. This is basic indexing. Start reading the tutorials.
help find

请先登录,再进行评论。

回答(2 个)

Star Strider
Star Strider 2014-12-11
Our friend accumarray may work best here. First, you would need to use the find command to get the index positions of the ‘1’ values in the longer vector to get my ‘ix1’ vector. My ‘rv’ vector corresponds to your 200-length vector. ‘A’ is the output column vector with zeros everywhere other than the positions where accumarray put the elements of ‘rv’. Note that ‘A’ is not the same length as your original NaN vector, so you will have to zero-pad it at the end if you need them to be equal. Transpose ‘A’ to be a row vector if necessary.
The code:
ix1 = randi(100,1,10); % Index Positions Of ‘1’ Values
rv = randi(20,1,10); % Values In ‘200’ Vector
A = accumarray(ix1', rv); % Assign Values To New Vector At ‘1’ Index Positions

Image Analyst
Image Analyst 2014-12-11
Here's another way:
% Set up/initialize data
indexesOf1s = sort(randperm(1500, 200))
m1505 = zeros(1,1505);
m1505(indexesOf1s) = 1;
m200 = randi(9, 1, 200);
% The above was all setup to get your two arrays.
% Now, do it. Put the values from the m200 array
% into the locations of the 1's of the m1505 array.
output = m1505; % Initialize length
logicalIndexesOf1s = m1505 == 1; % Find where m1505 is 1. Logical index.
output(logicalIndexesOf1s) = m200; % Stuff actual values in there.

类别

Help CenterFile Exchange 中查找有关 Data Types 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by