Removing elements and putting them in a different array

Hi everyone, My question is, how can I transform this k=[x1 x2 x3 x4 x5] into this a=[x2 x3] (random values from k) y b=[x1 x4 x5] (the rest), if sum(a)<35. In this example, ive managed to obtain matriz 'a':
clc
clear all
k=[19 16 11 15 8 8 7 14 6 11];
a=k(randperm(10));
i=11;
while 1
i=i-1;
y=randi(i);
if sum(a)<=35
break
else
a(:,y)=[];
end
end
However, when i want to get matriz 'b', it says 'Index exceeds matrix dimensions.'
clc
clear all
k=[19 16 11 15 8 8 7 14 6 11];
a=k(randperm(10));
i=11;
b=[];
while 1
i=i-1;
y=randi(i);
if sum(a)<=35
break
else
a(:,y)=[];
b=[b a(:,y)];
end
end
Thank you in advance for any advice you can offer.

2 Comments

doc setdiff
will give you b without the need of loops.
Thanks, but this command is not considering repeated values.

Sign in to comment.

 Accepted Answer

I would recommend that you use better variable names. Ones that have meaning.
The simplest way to solve your problem is to work with the indices of k instead of the values themselves.
k = [19 16 11 15 8 8 7 14 6 11];
indicestokeep = randperm(numel(k));
while true
if sum(k(indicestokeep)) <= 35
break;
else
indicestokeep = indicestokeep(1:end-1); %always remove the last one since order is random
end
end
a = k(indicestokeep)
b = k(setdiff(1:numel(k), indicestokeep))

1 Comment

Wow¡¡¡¡¡¡, it is much more than I expected. Thank you very much.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!