Avoiding loops for functions with arrays

1 view (last 30 days)
M
M on 29 Mar 2012
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)?

Answers (1)

Geoff
Geoff on 29 Mar 2012
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?

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!