Error using randi Size inputs must be scalar (Matlab)

I have entries parameters A and B, and I have to obtain C with for loop, where C is the random subset of B of size Ai
I program this
for i=1:n
C=randi([0,1],B,A(i));
end
But I get the error (Error using randi ==> inputs must be scalar)
How can I fixe the problem

1 件のコメント

Rik
Rik 2021 年 4 月 12 日
How are you making sure B and A(i) are positive scalars?

サインインしてコメントする。

 採用された回答

Jan
Jan 2021 年 4 月 12 日
編集済み: Jan 2021 年 4 月 12 日

0 投票

"C is the random subset of B of size Ai" :
for i = 1:n
% Without repetitions:
C = B(randperm(numel(B), A(i)));
% Or with repetitions:
C = B(randi([1, numel(B)], 1, A(i)));
... use C now
end

5 件のコメント

high speed
high speed 2021 年 4 月 12 日
@Jan What do you mean by repetitions
Rik
Rik 2021 年 4 月 12 日
If you have an array with these values:
B=[3 6 9];
Now you can take random samples in two ways:
C=[6 3 6]
%or
C=[6 9 3]
%or
C=[3 3 3]
%or
...
Or like this:
C=[3 6]
%or
C=[3 9]
%or
C=[9 6]
Jan
Jan 2021 年 4 月 13 日
@high speed: Simply try it:
B = 1:4;
% No repetitions:
C = B(randperm(numel(B), 4))
C = B(randperm(numel(B), 4))
C = B(randperm(numel(B), 4))
C = B(randperm(numel(B), 4))
% With repetitions:
C = B(randi([1, numel(B)], 1, 4));
C = B(randi([1, numel(B)], 1, 4));
C = B(randi([1, numel(B)], 1, 4));
C = B(randi([1, numel(B)], 1, 4));
Do you see it? With repetitions the values in the output can repeat. Then C can be longer than B. Without repetition, C is a permutation of the elements of B.
high speed
high speed 2021 年 4 月 13 日
@Jan Unfortunately, that's not what I want. Because I must program in a way that C is the random subset of B of size Ai. And in your example you didn't consider the size Ai
Jan
Jan 2021 年 4 月 13 日
@high speed: Sorry, what? Yes, in my example, I've used 4 to clarify what "repetition" means. You have asked for this detail. But the code in my answer does contain A(i).

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

タグ

質問済み:

2021 年 4 月 12 日

コメント済み:

Jan
2021 年 4 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by