add each element of one vector to each element of another vector

23 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 1 de Feb. de 2016
v=1:6;
ii=repmat(v',6,1),
jj= reshape(repmat(v,6,1),[],1);
out=[ii,jj]

Más respuestas (1)

Brendan Hamm
Brendan Hamm el 1 de Feb. de 2016
Editada: Brendan Hamm el 2 de Feb. de 2016
The essential idea here is that you want a 6x6 output containing the sums of the rows and columns (which will represent die1 and dce2 respectivelly). One thing you could do is replicate the values such that you have a 6x6 matrix for die1 values and a 6x6 matrix for die2 values and then add them:
[die1,die2] = meshgrid(1:6,1:6);
diceSum = die1 + die2;
There is a faster way to do this without the need for copying the "extra" data, called binary singleton expansion. This will take the 2 vectors and virtually expand them in their singleton dimensions before applying a function to the data. I say virtually as this copying is really never done, but the behavior is as if it did (You can think of the results of this expansion as what meshgrid created) which is why it is slightly faster than the above method.
diceSum2 = bsxfun(@plus,1:6,(1:6)') % Note that I transpose 1 so that both vectors are "expanded" in their singleton dimension.
The former is easier to understand, the latter is the fastest implementation.
If you really want these to be a vector:
diceSumVec = diceSum(:);
or even a sorted vector:
diceSumVec = sort(diceSum(:));
How many 7's are there?
isSeven = diceSumVec == 7; % A logical vector (1's in locations of 7's)
num7 = nnz(isSeven) % The number of non-zero elements is the number of 7's

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by