# Finding index in a set

1 view (last 30 days)
Md. Nazrul Islam Siddique on 17 Dec 2022
Edited: Stephen23 on 17 Dec 2022
Hello. I have these two sets.
x1 = [0 , 0, 1, 0]
x2 = [0, 0, 0, 0]
I want to randomly generate one in x2 except the index 3, where the vaule is x1. The output will be look like:
x1 = [0, 0, 1, 0]
x2 = [1, 0, 0, 0] or [0, 1, 0, 0] or [0, 0, 0, 1].
How can I do that?

Stephen23 on 17 Dec 2022
Edited: Stephen23 on 17 Dec 2022
Simple and efficient:
x1 = [0,0,1,0];
x2 = [0,0,0,0];
ix = find(~x1);
iy = randi(nnz(ix),1);
x2(ix(iy)) = 1
x2 = 1×4
0 0 0 1
Stephen23 on 17 Dec 2022
Edited: Stephen23 on 17 Dec 2022
Lets try it in a loop:
for k = 1:64
x1 = [0,0,1,0];
x2 = [0,0,0,0];
ix = find(~x1);
iy = randi(nnz(ix),1);
x2(ix(iy)) = 1
end
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
0 1 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 1 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
0 1 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
1 0 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 1 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 1 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
1 0 0 0
x2 = 1×4
0 0 0 1
x2 = 1×4
0 0 0 1
x2 = 1×4
1 0 0 0
x2 = 1×4
0 1 0 0
x2 = 1×4
1 0 0 0

Arif Hoq on 17 Dec 2022
Edited: Arif Hoq on 17 Dec 2022
one approach:
x1 = [0 , 0, 1, 0];
x2 = [0, 0, 0, 0];
% [value I]=find(x1==1);
b=perms(x1);
[row,col,v] = find(b(:,3));
b(row,:)=[];
c=b;
output=unique(c,'rows','stable')
output = 3×4
0 1 0 0 0 0 0 1 1 0 0 0
Arif Hoq on 17 Dec 2022
or using a function
x=4;
shiftv=2;
output=binvector(x,shiftv)
output = 1×4
0 1 0 0
function y=binvector(x,shiftv)
y=zeros(1,x);
y(shiftv)=1;
end

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!