MATLAB: Add each element of one vector to each element of another vector

MATLAB and Simulink Student Suiteprobability related

There are two dice, each with 1 to 6. I need to create all possibilities, ie, 1 through 36. I can use two vectors (1:6), but, to generate the 36 values, I have to use two for loops. Is there a clean way to do element-wise vector addition such that each element of vector 1 is added to all 6 values of vector 2? The simplest code I came up with is: Given x= (1:6), y = (1:6). These represent 6 sides of a dice. for i = 1:6 z1(i,:) = x(i)+y; end But, this creates a two-dim matrix. Also, if I want to find how many 7's in this, it requires a while or for loop. Any cleaner way to do this? Thanks. %Convert into 1-dim vector and count # of 7's . z3 = z1(:); count = 0; for k = 1:size(z3) if (z3(k) == 7) count = count +1; end end

Best Answer

v=1:6;
ii=repmat(v',6,1),
jj= reshape(repmat(v,6,1),[],1);
out=[ii,jj]