ehsun
ehsun

Reputation: 157

How can I create/index this matrix in a more efficient way?

I have written a MATLAB code that works okay but I want to write it in a more efficient way (I don't want to repeat myself and I want to make it dry).

At first I create a matrix of ones (28*8) and then I want to change some of its elements to minus ones.

Here is the code:

a=ones(28,8);
for i=1:7
    j=1;
    a(i,j)=-1;
end
for i=8:13
    j=2;
    a(i,j)=-1;
end
for i=14:18
    j=3;
    a(i,j)=-1;
end
for i=19:22
    j=4;
    a(i,j)=-1;
end
for i=23:25
    j=5;
    a(i,j)=-1;
end
for i=26:27
    j=6;
    a(i,j)=-1;
end
for i=28:28
    j=7;
    a(i,j)=-1;
end

Upvotes: 1

Views: 39

Answers (1)

gnovice
gnovice

Reputation: 125854

All of that code can actually be reduced to a single line:

a = repelem(ones(7, 8)-2.*eye(7, 8), 7:-1:1, 1);

How it works: The solution above first creates a 7-by-8 matrix of ones, then subtracts off a 7-by-8 identity matrix (ones on the main diagonal) multiplied by two. This gives a matrix of ones with negative ones on the main diagonal. It then uses repelem to replicate each row by an amount of 7 for the first row, 6 for the second, and so on.

a = 

    -1     1     1     1     1     1     1     1
    -1     1     1     1     1     1     1     1
    -1     1     1     1     1     1     1     1
    -1     1     1     1     1     1     1     1
    -1     1     1     1     1     1     1     1
    -1     1     1     1     1     1     1     1
    -1     1     1     1     1     1     1     1
     1    -1     1     1     1     1     1     1
     1    -1     1     1     1     1     1     1
     1    -1     1     1     1     1     1     1
     1    -1     1     1     1     1     1     1
     1    -1     1     1     1     1     1     1
     1    -1     1     1     1     1     1     1
     1     1    -1     1     1     1     1     1
     1     1    -1     1     1     1     1     1
     1     1    -1     1     1     1     1     1
     1     1    -1     1     1     1     1     1
     1     1    -1     1     1     1     1     1
     1     1     1    -1     1     1     1     1
     1     1     1    -1     1     1     1     1
     1     1     1    -1     1     1     1     1
     1     1     1    -1     1     1     1     1
     1     1     1     1    -1     1     1     1
     1     1     1     1    -1     1     1     1
     1     1     1     1    -1     1     1     1
     1     1     1     1     1    -1     1     1
     1     1     1     1     1    -1     1     1
     1     1     1     1     1     1    -1     1

Upvotes: 2

Related Questions