How to create multiple matrices with different sizes without a loop?
조회 수: 3 (최근 30일)
이전 댓글 표시
Say I have a matrix with M elements. In this case its 3.
A = [1 2 3];
And I want to create M vectors with N random numbers from the interval 0 to each of the element in A.
X = randi([0,A(1)], 1, N)
Y = randi([0,A(2)], 1, N)
Z = randi([0,A(3)], 1, N)
How can I do this without using loops? Is it possible?
댓글 수: 0
채택된 답변
James Tursa
2020년 10월 7일
You will either need to use loops, or hide the loops behind a function call (e.g., arrayfun):
result = arrayfun(@(x)randi([0 x],1,N),A,'uni',false);
댓글 수: 0
추가 답변 (1개)
Walter Roberson
2020년 10월 7일
N = 100;
A = [1 2 3];
M = length(A);
XYZcell = num2cell(floor(rand(M, N) .* (A(:)+1)), 2);
[X, Y, Z] = XYZcell{:};
counts = accumarray(Z(:)+1, 1);
bar(0:3, counts)
댓글 수: 1
Walter Roberson
2020년 10월 7일
Note: this method is very slightly biased against 0 -- but not enough that you would notice.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
