How I can choose randomly value from cell?

조회 수: 24 (최근 30일)
Mira le
Mira le 2019년 12월 7일
댓글: Mira le 2019년 12월 8일
>> 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

채택된 답변

David Hill
David Hill 2019년 12월 7일
Why not just,
a=cell2mat(SI);
b=a(randi(length(a)));%b is a random value inside all of SI
  댓글 수: 2
Mira le
Mira le 2019년 12월 7일
can I use it in struct?
Mira le
Mira le 2019년 12월 7일
Cell contents reference from a non-cell array object.
Error in cell2mat (line 42)
cellclass = class(c{1});
Error in Evaluation (line 87)
a1=cell2mat(TI(q).Si);
This error appear when i use cell2mat
TI is struct and Si is field of TI of type cell

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2019년 12월 7일
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

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by