error using randi: size inputs must be scalar

14 次查看(过去 30 天)
I apologize for the incredibly basic question I'm assuming it has something to do with Matlab versions but this old code that is very simple I cannot seem to make it work.
for n = 1:4
a{n} = randint(n,n,[0,9]);
b{n} = randint(n,n,[0,9]);
fprintf(n = %d:\n’, n), A = a{n}, B = b{n},
end
I changed randint to randi per recommendation of matlab.
EDIT:
I was able to make it work by manipulating the code to this.
for n=1:4
a{n}= randi(9,n)
b{n}= randi(9,n)
fprintf('n = %d:\n', n), A = a{n}, B = b{n},
end
now generates two 4x4 matrices with random numbers between [0,9].
Can somebody explain to me why though? The first formatting looks better than the second one logically.

回答(3 个)

Joseph Cheng
Joseph Cheng 2017-4-24
you actually want to do
for n=1:4
a{n}= randi(10,n)-1;
b{n}= randi(10,n)-1;
fprintf('n = %d:\n', n), A = a{n}, B = b{n},
end
as randi(9) is "Generate integer values from the uniform distribution on the set 1:9."
and what you have should be correct and does more than just 2 4x4 matrices. if you scroll up in the command window (as every calculation is displayed because there is no ';' at the end of the lines)
you should see that a and b is a cell array with varying size matrices in each cell
>> a
a =
[5] [2x2 double] [3x3 double] [4x4 double]
>> b
b =
[2] [2x2 double] [3x3 double] [4x4 double]

George Amrhein
George Amrhein 2017-4-24
Sorry just trying to understand, your edit makes it so i can get the distribution on the set 0:9 in my matrix correct? instead of 1:9 as it was before

Walter Roberson
Walter Roberson 2017-4-24
randi([0 9], n, n)

类别

Help CenterFile Exchange 中查找有关 Simulink Functions 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by