# How can I match these vector values?

1 Ansicht (letzte 30 Tage)
Robert am 11 Dez. 2014
Beantwortet: Image Analyst am 11 Dez. 2014
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 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
John D'Errico am 11 Dez. 2014
It is time for you to learn the basics of MATLAB. This is basic indexing. Start reading the tutorials.
help find

Melden Sie sich an, um zu kommentieren.

### Antworten (2)

Star Strider am 11 Dez. 2014
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
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Image Analyst am 11 Dez. 2014
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.
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Data Types finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by