MATLAB Answers

Creating indivdual column vectors based off a location vector

1 view (last 30 days)
Christopher on 16 Oct 2013
Commented: Yannick on 17 Oct 2013
Hello all,
I am trying to figure out how to do this and can't come up with a good way to do it. What I am trying to do is break up this long column vector up, based on a location vector. So, I have a long column vector of data ( roughly) 10000 x 1. I then have a location vector that contains locations where I want to break up the column vector. It looks something like this:
I am trying to create individual column vectors of the data based on the location vector. So for example I will end up with column vectors such as:
etcc.... Based off the location vector
The problem is, I need a way to automate this, because the location vector actually contains many locations. I was trying to do this with a for loop, but I keep getting stuck.


Sign in to comment.

Answers (1)

Yannick on 16 Oct 2013
Hi, here's a way to do it using ARRAYFUN:
initialIndices = location(1:end-1);
finalIndices = location(2:end);
C = arrayfun(@(i,j)data(i:j),initialIndices,finalIndices,'UniformOutput',false)
Then, C{1} would correspond to your first matrix ( a1 in the description), C{2} to the next chunk, and so on. Maybe there are better ways, but this is one. A FOR loop is certainly another way of doing it.
Here are some useful doc pages:


Christopher on 16 Oct 2013
I like that, but I still have to manually enter C{1}, C{2}, etcc.. I was trying to have them output automatically, because there is around 50 different a's that I would have to type out.
I couldn't figure out how to get it work in a for loop. I would think it would be easy, but it's not obvious.
Yannick on 17 Oct 2013
This piece of code fully automates the process of breaking the original array up into chunks, and has the benefit of collecting the chunks into a single data structure, the cell array C. It is preferable to have one data structure you can index into, as opposed to 50 different variables. So I don't see any benefit to doing a1=C{1}, a2=C{2}, and so on for all chunks.
Here's an example to illustrate this. Say you have your data in the form of a cell array, and you need to do some computation on chunks 10 through 20. You can easily do the following:
for k = 10:20
Easy. Now imagine that instead, you have a bunch of variables a1, a2, etc. How do you do this easily in a loop?
Now, there is a way, but it is NOT recommended at all. If you read that link carefully, you should take away two things:
  1. eval should be avoided (luckily this is possible in the vast majority of cases);
  2. for your particular case, cell arrays (or perhaps structure arrays) seem like the way to go.
If you decide to ever use eval, you didn't hear it from me.
I hope this helps clarify my suggestion!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by