Finding an element of a cell in a cell array

1 view (last 30 days)
If I have a cell array:
C= [ [1 2 3], [2 2 3], [5 2 7 10 2 1], [12 10 22 0] ,[4 7 5] ]
I want to locate all of the 1's ( so C{1}(1), and C{3}(6) ), and replace them with two random numbers. How might I go about doing that?

Accepted Answer

Cedric
Cedric on 1 Jul 2014
Edited: Cedric on 1 Jul 2014
A simple loop would do
C = { [1 2 3], [2 2 3], [5 2 7 10 2 1], [12 10 22 0] ,[4 7 5] } ;
for cId = 1 : numel( C )
is1 = C{cId} == 1 ;
if any( is1 )
C{cId}(is1) = rand( 1, nnz(is1) ) ;
end
end
outputs C with..
>> C{1}
ans =
0.6324 2.0000 3.0000
>> C{2}
ans =
2 2 3
>> C{3}
ans =
5.0000 2.0000 7.0000 10.0000 2.0000 0.0975
If you need a random integer -> doc randi

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!