how to use "randi" in specific case?
4 次查看(过去 30 天)
显示 更早的评论
Hi!
i want to ask you if it is possible to use "randi" in this case:
i have a binary matrix A (m*n), each row has just "1" and other elements are set to "0", i want to put randomly in the "1" position a value from this range for example [10,15,20,25].
i'm asking how can i remove the case of seeing the same value in the same column or two same values in two successive columns.
for example:
0 0 10 0 0 0 0 0 0 0
0 0 10 0 0 0 0 0 0 0
0 0 0 15 0 0 0 0 0 0
0 0 0 20 0 0 0 0 0 0
0 0 0 10 0 0 0 0 0 0
0 0 0 0 25 0 0 0 0 0
0 0 0 0 0 0 20 0 0 0
0 0 0 0 0 0 0 15 0 0
0 0 0 0 0 0 0 0 10 0
0 0 0 0 0 0 0 0 10 0
0 0 0 0 0 0 0 0 0 15
0 0 0 0 0 0 0 0 0 25
as you see the third column i have the same value "10" ,also in the fourth i have the same value of previous column, i want to remove this case.
i'll appreciate any help, thank you very much.
4 个评论
Torsten
2022-11-30
If your binary matrix had, e.g. (five 1's in some column) or (four 1's in some column and at least one 1 in the preceeding or next column), you couldn't do what you try to do. And then ?
采纳的回答
Voss
2022-11-30
Maybe something like this (the example A requires at least 5 values, e.g., [10 15 20 25 30]):
A = [ ...
0 0 1 0 0 0 0 0 0 0; ...
0 0 1 0 0 0 0 0 0 0; ...
0 0 0 1 0 0 0 0 0 0; ...
0 0 0 1 0 0 0 0 0 0; ...
0 0 0 1 0 0 0 0 0 0; ...
0 0 0 0 1 0 0 0 0 0; ...
0 0 0 0 0 0 1 0 0 0; ...
0 0 0 0 0 0 0 1 0 0; ...
0 0 0 0 0 0 0 0 1 0; ...
0 0 0 0 0 0 0 0 1 0; ...
0 0 0 0 0 0 0 0 0 1; ...
0 0 0 0 0 0 0 0 0 1];
vals = [10 15 20 25 30];
[m,n] = size(A);
n_vals = numel(vals);
is_used = false(1,n_vals);
is_used_previous = false(1,n_vals);
for jj = 1:n
idx = find(A(:,jj));
for ii = 1:numel(idx)
if all(is_used | is_used_previous)
continue
end
unused_val_idx = find(~is_used & ~is_used_previous);
new_val_idx = randi(numel(unused_val_idx));
A(idx(ii),jj) = vals(unused_val_idx(new_val_idx));
is_used(unused_val_idx(new_val_idx)) = true;
end
is_used_previous = is_used;
is_used(:) = false;
end
disp(A);
更多回答(1 个)
David Hill
2022-11-30
n=10;%length of matrix
l=[10 15 20 25];
m=zeros(length(l),n);
r1=randperm(length(l));r2=randperm(n,length(l));r3=randperm(length(l));
for k=1:length(l)
m(r1(k),r2(k))=l(r3(k));
end
m
7 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!