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 件のコメント

Adam
Adam 2018 年 2 月 6 日
doc setdiff
will give you b without the need of loops.
gonzalo salazar
gonzalo salazar 2018 年 2 月 6 日
Thanks, but this command is not considering repeated values.

サインインしてコメントする。

 採用された回答

Guillaume
Guillaume 2018 年 2 月 6 日

1 投票

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 件のコメント

gonzalo salazar
gonzalo salazar 2018 年 2 月 6 日
Wow¡¡¡¡¡¡, it is much more than I expected. Thank you very much.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by