Splitting a large vector into smaller ones of random size

6 次查看(过去 30 天)
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 个评论
John D'Errico
John D'Errico 2017-3-1
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 2017-3-1
编辑:Stephen23 2017-3-1
@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.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2017-3-1
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 个评论
paco
paco 2017-3-1
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 2017-3-1
@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.

请先登录,再进行评论。

更多回答(2 个)

Andrei Bobrov
Andrei Bobrov 2017-3-2
out = mat2cell(index(:)',1,diff([find([true;diff(index(:)) > 1]);numel(index)+1])');
  2 个评论
Jan
Jan 2017-3-2
@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
John BG 2017-3-1
编辑:John Kelly 2017-3-2
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 个评论
Walter Roberson
Walter Roberson 2017-3-3
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 2017-3-4
编辑:John BG 2017-3-4
this guy paco, doesn't say anything, not even hello

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by