choose 2 index separately inside cell
Infos
Cette question est clôturée. Rouvrir pour modifier ou répondre.
Afficher commentaires plus anciens
index={[1,2,5,9,10,13,17,18,21],[4,5,7,12,13,15,18,20,21],[3,4,6,11,12,14,18,19,20],[8,16,20,22]};
amount={[10,11,12,10,11,10,12,13,20],[11,15,12,13,11,10,15,13,12],[13,16,16,17,11,10,15,13,12],[4,5,6,10]};
change_amount=cellfun(@(m) m/2, index, 'UniformOutput', false);
changed_num=2;
p=cellfun(@(m) randperm(size(m,2)), index, 'UniformOutput', false);
changed_mes=cellfun(@(m) m(1:changed_num), p, 'UniformOutput', false);
I do not want repeated index in changed_mes(does not have any intersection). if changed_mes become {[3,9],[9,3],[3,2],[1,4]} as [3,9] and [9,3] is same, need to do randperm again. so I wrote this code
finally i can change amount of 2 mes in each array
result=cellfun(@(m,u) m(u)=0, change_amount,p 'UniformOutput', false);
but does not give correct result
1 commentaire
You have posted some code, which does not do, what you want. It is not easy to find out, what you consider as "correct result". It would be much easier if you mention, what you want to achieve actually. What is the wanted result?
The excessive use of cellfun makes it much harder to understand and debug the code. Maybe some simple loops are ways better. Optimize the code with some smart cellfun calls only after you have an already working solution and if you can prove, that it is really faster.
Réponses (1)
Jan
le 22 Fév 2019
index = {[1,2,5,9,10,13,17,18,21],[4,5,7,12,13,15,18,20,21],[3,4,6,11,12,14,18,19,20],[8,16,20,22]};
amount = {[10,11,12,10,11,10,12,13,20],[11,15,12,13,11,10,15,13,12],[13,16,16,17,11,10,15,13,12],[4,5,6,10]};
num = 2;
result = cell(size(amount));
for k = 1:numel(result)
m = amount{k} / 2;
... ??? I cannot follow the rest of the code
... You want a set of [num] randomly selected indices to be set to 0, correctly?
end
Sorry, I tried to recreate the code by a simple loop, but failed to understand the logic.
2 commentaires
Jan
le 25 Fév 2019
A clear description of what the code should do would be a good idea, preferrably as comments. A samll simplification:
index = [1,2,5,9,10,13,17,18,21];
amount = [10,11,12,10,11,10,12,13,20];
num = 2;
p = randperm(numel(index));
changed_mes_index = p(1:num);
b = amount / 2;
b(p(num+1:end)) = 0;
result = amount + b;
I have no idea, how this problem can be modified to work with cells.
You go forward with mentioning "the other problem". What exactly is the first problem?
If you want the elements in the cell array changed_mes to be unique, create it accordingly:
num = 2; % a [1x2] vector per cell element
numC = 4; % Number of cell elements
maxV = 20; % The maximum value
V = (1:maxV);
V = V(randperm(maxV, num * numC));
changed_mes = num2cell(reshape(V, [], 2), 2);
Cette question est clôturée.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!