SteveL
SteveL

Reputation: 3389

Matlab, matrix dimensions must agree

I need to create a matrix where I have points in a 0-1 range simulating a xor gate like in the picture bu points should exist in upper left and bottom right corners too.

enter image description here

I am using this code:

    pats = [0.4*rand(n/4,2);
            0.4*rand(n/4,2)+0.6;
            0.4*rand(n/4,2)+[0 0.5];
            0.4*rand(n/4,2)-[0 0.5]+0.6];

And I get the following error:

Warning: Size vector should be a row
vector with integer elements. 
> In main at 24 
Warning: Size vector should be a row
vector with integer elements. 
> In main at 24 
Warning: Size vector should be a row
vector with integer elements. 
> In main at 24 
Warning: Size vector should be a row
vector with integer elements. 
> In main at 24 
Error using  + 
Matrix dimensions must agree.

Error in main (line 24)
        pats = [0.4*rand(n/4,2);

Upvotes: 1

Views: 172

Answers (1)

MattG
MattG

Reputation: 1426

The element wise addition doesn't work for your randn(n/4,2) + [0 0.5] because you are trying to add a n/4 by 2 matrix to a 1 by 2 matrix. You need to use bsxfun:

pats = [0.4*rand(n/4,2);
    0.4*rand(n/4,2)+0.6;
    bsxfun(@plus,0.4*rand(n/4,2),[0 0.5]);
    bsxfun(@minus,0.4*rand(n/4,2),[0 0.5]) + 0.6];

The function bsxfun(@plus, A, b) will add the i-th element of b to the i-th column of matrix A.

Upvotes: 2

Related Questions