Splitting a large vector into smaller ones of random size

조회 수: 5 (최근 30일)
paco
paco 2017년 3월 1일
편집: John BG 2017년 3월 4일
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 :-)
Andrei Bobrov
Andrei Bobrov 2017년 3월 3일
Wow! Jan you are a poet! I like your comment.

댓글을 달려면 로그인하십시오.


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에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by