# how i will choose a random element of a matrix and then find in which row,column it is

23 views (last 30 days)
Giannakis Stoukas on 31 Mar 2015
Edited: Stephen23 on 1 Apr 2015
I have a matrix A and i want to insert to a variable a random element of this matrix,except two numbers 0 and 1.Then i want to find in which row/column the element is

Image Analyst on 31 Mar 2015
You can use randperm() to get a random location. Get one location to extract the random element of A, and another location to get the location where you want to insert that random element. I don't know what "except two numbers 0 and 1" means - please clarify. To find where a certain integer lives in A, use find
[rows, columns] = find(A == yourDesiredNumber);
##### 2 CommentsShowHide 1 older comment
Image Analyst on 31 Mar 2015
Try code like this:
loopCounter = 0; % Failsafe.
maxTries = 100000
while loopCounter < maxTries
randomElement = A(randomRow, randomColumn)
if randomElement <> 0 && randomElement <> 1
% Success! We found a good element. Quit looking now.
break;
end
loopCounter = loopCounter + 1;
end
if loopCounter == 0
message = sprintf('No non-0 or non-1 elements found after %d tries.',...
loopCounter);
uiwait(warndlg(message));
end

Jon on 31 Mar 2015
I think something like this would work.
is01 = true; initialize flag for while loop
while is01
ind=randi(numel(A)); % Pick the random element
is01 = ismember(A(val),[0 1]); % see if selected element is 0 or 1
end
[row,col]=ind2sub(size(A),ind); % get the row and column of the selected element
val=A(ind); % or A(row,col), store the value of the random element in val
If the selected element is 0 or 1, is01 will stay true and the loop will continue. If the selected element is not 0 or 1, is01 will become false and the loop will terminate with the index of the random element stored in ind and its value in val. The ind2sub command converts the index to a row and column reference.

Stephen23 on 31 Mar 2015
Edited: Stephen23 on 1 Apr 2015
Instead of using slow loops this can be achieved using fully vectorized code, by only generating the required indices:
>> A = [2,3,1;8,7,6;5,4,0];
>> B = find(A>1);
>> X = randi(numel(B));
>> A(B(X))
ans =
5
>> [r,c] = ind2sub(size(A),B(X))
r =
3
c =
1
This code is much faster than using loops, and makes changing the exclusion condition very easy. It also makes it easy to randomly select multiple elements (not just one) by providing the optional size input to randi:
>> X = randi(numel(B),[1,23]);
>> A(B(X).')
ans =
7 3 6 8 5 2 6 7 3 7 3 7 3 4 3 6 8 2 2 2 5 3 5
>>[r,c] = ind2sub(size(A),B(X).')
r =
2 1 2 2 3 1 2 2 1 2 1 2 1 3 1 2 2 1 1 1 3 1 3
c =
2 2 3 1 1 1 3 2 2 2 2 2 2 2 2 3 1 1 1 1 1 2 1
Note that zero and one do not appear in the output matrix! The transpose is optional.