Avoiding loops for functions with arrays

조회 수: 1 (최근 30일)
M
M 2012년 3월 29일
Hi
I have to use the following code snippet in a program:
M = [2 4 6 8];
Data = randint(1,10,M);
This gives an error saying "The IRANGE parameter should contain no more than two elements."
One way to solve this is to use a loop for each element of M. How do I avoid using a loop here and calculate Data(i) for each M(i)?

답변 (1개)

Geoff
Geoff 2012년 3월 29일
Do you want a 1x10 matrix containing random values from M? There are a number of ways to do this.
Using randint, you need to check the documentation. Like the error says, the third parameter requires a 1x2 vector [low,high]. Since your vector M happens to have a pattern, you could use:
Data = randint(1, 10, [1 4]) * 2;
But this isn't very nice because it makes assumptions about M.
Why don't you instead use randint to generate a 1x10 matrix of random indices into M?

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by