## Creating vectors from rows of matrix

### Narayan Bhusal (view profile)

on 4 Jun 2019
Latest activity Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 4 Jun 2019

I can reshape a vector into a matrix, but I need to create a bunch of independent vectors from a matrix that I can recall individually. Ultimately, I will be counting the number of peaks in these vectors, and making a histogram of the counts, so I can't just overwrite a variable each time.
b=20; % number of data points you want
V=rand(1,100); % input data
r= reshape(V,[],b); % creates matrix with 'b' columns and the number of rows necessary to make reshape work
for i = 1:size(r,1)
SubVector = r(i,:); % needs to create a separate vector from each row of 'r' with its own unique name
end
In practice, V will be millions of numbers long and vary in size each time data is taken; so just manually making each variable and referencing to a row is not an option. As is, SubVector will only return the last row of r. If I try SubVector(i), I get an error saying the left and right sides have a different number of elements. Ideally, I would get a series of variables that I can reference to with SubVector(i). Thanks for any help.

#### 1 Comment

Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 4 Jun 2019
" I need to create a bunch of independent vectors from a matrix that I can recall individually."
That is exactly what indexing is for. Indexing is simple, neat, easy to debug, and very efficient.
"Ideally, I would get a series of variables that I can reference to with SubVector(i)"
Dynamically accessing variable names is one way that some beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
There is no point in duplicating that data in memory and using slow methods to access it.
Just use indexing.

R2019a

on 4 Jun 2019