changing elements of a multidimensional array using matlab

3 views (last 30 days)
Hey guys, Im kind of lost. I am making a m*n zero matrix. I want to change each element into either 1,2 or 3. If the array is 1 by n i can do it but i can't do it for m*n i am using for loops this is what i would did.
x=zeros(1,randi(10)) n=length(x) for m=1:n x(m)=randi(3) end This works for 1*n but what would i do if its like 2 by n or bigger i tried this
x=zeros(2,randi(10)) [r,c]=size(x) for m=1:r for p=1:c x(p)=randi(3) end x(m)=randi(3) end this only changes the first 3 elements and the 1st two of the second row. Please help thanks

Accepted Answer

Roger Stafford
Roger Stafford on 4 Dec 2013
m + randi(10);
n = randi(10);
x = zeros(m,n);
for p = 1:m
for q = 1:n
x(p,q) = randi(3);
end
end
You could also dispense with all this nonsense and simply do this:
x = randi(3,randi(10,1,2));

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!