How I can choose randomly value from cell?
10 views (last 30 days)
Show older comments
>> SI
SI =
1×2 cell array
[1×2 double] [1×2 double]
>> for i=1:numel(SI)
disp(SI{i});
end
1 2
2 3
I want to choose value randomly from SI
for example the value is just one value among 1 2 like 1 or 2
0 Comments
Accepted Answer
David Hill
on 7 Dec 2019
Why not just,
a=cell2mat(SI);
b=a(randi(length(a)));%b is a random value inside all of SI
More Answers (1)
Image Analyst
on 7 Dec 2019
Here's one way, if you need to get the value within a loop where you're doing other things:
SI = {[1, 2], [2, 3]}
for k = 1 : length(SI)
% Extract the numerical array from the cell.
thisCellsContents = SI{k};
% Get a random index from that array
randomIndex = randperm(numel(thisCellsContents), 1);
% Get the value from the array.
theValues(k) = thisCellsContents(randomIndex);
% Show what we got
fprintf('Randomly picked %f from cell #%d\n', ...
theValues(k), k);
end
% Show all the values in the command window:
theValues
For example, you'll see:
SI =
1×2 cell array
{1×2 double} {1×2 double}
Randomly picked 2.000000 from cell #1
Randomly picked 3.000000 from cell #2
theValues =
2 3
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!