creating multiple variables from a vector

5 visualizaciones (últimos 30 días)
shobhit mehrotra
shobhit mehrotra el 20 de Ag. de 2014
Editada: Andrei Bobrov el 21 de Ag. de 2014
i have a vector [185 186 188 189 192 247 248 249 250 251 252 253 254 255 625 626....] i want to group all of terms that are within 15 numbers apart together. for example vector1 = [185 186 188 189 192] vector2= [247 248 249 250 251 252 253 254 255] vectorn = [625 626....]

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 20 de Ag. de 2014
Shobhit - rather than creating multiple variables (which is possible but gets messy), why not just create a cell array of these vectors instead? That way you have all of the vector data within one array.
% create the vector of data to break apart
V = [185 186 188 189 192 247 248 249 250 251 252 253 254 255 625 626];
% sort the data in ascending order
V = sort(V);
% create the data vector cell array
data = {};
k = 1;
% continue looping until all elements have been split into vectors
while true
% find the index of the first element that is 15 larger than the first V(1)
idx = find(V>V(1)+15,1);
if ~isempty(idx)
% extract the elements
data{k} = V(1:idx-1);
% reset V, removing those that have been extracted
V = V(idx:end);
% increment to the next k
k = k + 1;
else
% else there is no element in V that is 15 larger, so all remaining
% elements are together
data{k} = V(1:end);
% break out of loop
break;
end
end
Try the above and see what happens!

Más respuestas (2)

Guillaume
Guillaume el 20 de Ag. de 2014
Editada: Guillaume el 20 de Ag. de 2014
An alternative way of doing this:
[~, binnumber] = histc(V, min(V):15:max(V)+15);
vector = cell(1, max(binnumber)); %optional
for bin = 1:max(binnumber)
vector{bin} = V(find(binnumber == bin));
end

Andrei Bobrov
Andrei Bobrov el 20 de Ag. de 2014
Editada: Andrei Bobrov el 21 de Ag. de 2014
EDIT
a = [185 186 188 189 192 247 248 249 250 251 252 253 254 255 625 626] ;
m = ceil(max(a))+1;
k = min(a):15:m;
k(end) = m;
[~,ii] = histc(a,k);
ii = cumsum([1;diff(ii(:))~=0]); % OR [~,~,ii] = unique(ii);
out = accumarray(ii(:),a(:),[],@(x){x})

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by