Info
This question is closed. Reopen it to edit or answer.
Creating indivdual column vectors based off a location vector
1 view (last 30 days)
Show older comments
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:
location=[2;200;360;500;700;850;900]
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:
a1=data(2:200)
a2=data(200:360)
a3=data(360:500)
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.
0 Comments
Answers (1)
Yannick
on 16 Oct 2013
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:
2 Comments
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
performComputationOnChunk(C{k});
end
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:
- eval should be avoided (luckily this is possible in the vast majority of cases);
- 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!
This question is closed.
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!