Splitting a large vector into smaller ones of random size
6 views (last 30 days)
Show older comments
I have "larger" vector made of indexes of an another array so all its component are in order and whole numbers. These numbers forms smallers continous sequences that depends on the signal I'm working on, and therefore can be considered more or less random. My goal is to isolate these smaller sequences. I'm pretty sure there's an easy way to do that but I can't figure it out :/
ex: index = [1 13 14 15 16 17 36 37 38 41 42 43 44 46 47 51 52 53 ...]
I would like to get:
index_1 = [1]
index_2 = [13 14 15 16 17]
index_3 = [36 37 38] . . .
What i have for now only works if these sequences are of equal size :/
count=0; cl=1;
A=zeros(16,5);
for i= 2:length(index);
h1=index(i-1);
h2=index(i);
if(h2-h1)>1;
count=(count+1);
A(:,count)=index(cl:i-1);
cl=i;
end
end
2 Comments
John D'Errico
on 1 Mar 2017
It is a BAD idea to set up multiple numbered variables. Your code will be slow, inefficient, buggy, difficult to work with if you do.
Instead, learn to use tools like cell arrays, so that you can store vectors and arrays of any shape and size in each cell. Then you simply use curly braces {} for indexing. ONE variable, instead of dozens of numbered variables.
Accepted Answer
Jan
on 1 Mar 2017
Don't do this. See http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. Prefer a cell array A{1}, A{2}, ... Use something like this:
match = (diff(index) > 1);
A = cell(1, sum(match)); % Pre-allocate, care about the margins
for k = find(match)
A{k} = ...
end
This is just the structure, not running code.
2 Comments
Jan
on 1 Mar 2017
@paco: Then this forum is the best place for you to ask such questions. welcome at Matlab and in this forum.
I've voted for your question, because you've explained exactly, what you want to do and posted code to demonstrate your intentions.
More Answers (2)
Andrei Bobrov
on 2 Mar 2017
out = mat2cell(index(:)',1,diff([find([true;diff(index(:)) > 1]);numel(index)+1])');
2 Comments
Jan
on 2 Mar 2017
@Andrei: +1. I like your solution, because it looks like C code: as if somebody had rolled an angry armadillo over the keyboard :-)
John BG
on 1 Mar 2017
Edited: John Kelly
on 2 Mar 2017
Hola Paco
tal y como se indica en el HELP del MATLAB, si sigues las recomendaciones indicadas, 'evalin' es un comando muy popular y muy potente para generar código 'on the loop', un tema avanzado que los expertos no acostumbran a largar si no es pagando por sus servicios.
mira si las siguientes líneas te son de utilidad:
1. generación de la respuesta numérica
index = [1 13 14 15 16 17 36 37 38 41 42 43 44 46 47 51 52 53];
dindex=[1 logical(diff(index)-1) 1]
[n,v]=find(dindex>0)
s=diff(v)
for k=1:1:numel(s) % generating the n umerical answer
L{k}=(index(v(k))-1)+[1:1:s(k)]
end
verificando
L{:}
ans =
1
ans =
13 14 15 16 17
ans =
36 37 38
ans =
41 42 43 44
ans =
46 47
ans =
51 52 53
2. generación dinámica de las variables
str1=repmat('index_',numel(L),1) % generating variable name headers
N0=num2str(100+[1:1:numel(L)]');N0(:,1)=[] % generating numerals in variable names
N1=repmat('=[',numel(L),1)
N2=repmat(']',numel(L),1)
str2=[str1 N0 N1]
for k=1:1:numel(L)
L2=[str2(k,:) num2str(L{k})]
evalin('base',[L2 ']'])
end
Comentario: he generado los nombres de variables con 2 dígitos, con '0' hasta llegar a la decena, porque habiendo requerido algo similar, encontré de utilidad poder disponer de las variables por orden alfabético. Si las nombras 'index_1' 'index_2' .. 'index_10' 'index_11' .. si las necesitas ordenadas alfabéticamente las primeras 9 variables quedarían relegadas por tener nombres más cortos. Si quieres los nombres de las primeras 9 variables sin '0' no es problema, puedo variar el script.
atentamente, a la espera de respuesta
John BG
3 Comments
Walter Roberson
on 3 Mar 2017
The experts do not usually refer to evalin() because using it is expensive in terms of the time spent debugging, the insecurity, the high likelihood of hidden bugs, and the extra time cost it often imposes.
Sometimes you need to use evalin('caller') to extend MATLAB syntax, such as the way the "syms" command is implemented, but it has many of the same dangers as eval() does.
Avoiding evalin() is a way of making projects less expensive, as the cost of fixing bugs later typically far exceeds the cost of writing code correctly early.
The Systems Sciences Institute at IBM has reported that “the cost to fix an error found after product release was four to five times as much as one uncovered during design, and up to 100 times more than one identified in the maintenance phase.”
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!