Clear Filters
Clear Filters

Splitting a large vector into smaller ones of random size

6 views (last 30 days)
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
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.
Stephen23
Stephen23 on 1 Mar 2017
Edited: Stephen23 on 1 Mar 2017
@paco: creating lots of variable names dynamically is not a good way to write code:
As everyone here has already said, you should use a cell array.

Sign in to comment.

Accepted Answer

Jan
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
paco
paco on 1 Mar 2017
Thank you for your answer! i've started matlab recently so I'm still learning about good and bad practices. I'll try to implement this now.
Jan
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.

Sign in to comment.

More Answers (2)

Andrei Bobrov
Andrei Bobrov on 2 Mar 2017
out = mat2cell(index(:)',1,diff([find([true;diff(index(:)) > 1]);numel(index)+1])');
  2 Comments
Jan
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 :-)

Sign in to comment.


John BG
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
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.”
John BG
John BG on 4 Mar 2017
Edited: John BG on 4 Mar 2017
this guy paco, doesn't say anything, not even hello

Sign in to comment.

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!