Raza Mehdi
Raza Mehdi

Reputation: 35

Create matrix of some repeating numbers

EN = 10;
etable = [1,2,3,4,5,6;
4,5,6,7,8,9;
7,8,9,10,11,12;
10,11,12,13,14,15;
13,14,15,16,17,18;
16,17,18,19,20,21;
19,20,21,22,23,24;
22,23,24,25,26,27;
25,26,27,28,29,30;
28,29,30,31,32,33];

Is it possible to make a for loop in which I just change the EN value and it automatically creates etable? Because I have to make EN 50 so it'll not be good to write 50 lines in etable.

I tried in this way:

EN = 10;
c = 1:EN;
nodes = zeros(size(c',1),2);
for i = 1:length(c)
   nodes(i,1) = i;
   nodes(i,2) = i+1;
end
etable = zeros(size(c',1),6);
for i = 1:size(nodes,1)
etable(i,1) = 2*nodes(i,1)-1;
etable(i,2) = 2*nodes(i,1);
etable(i,3) = 2*nodes(i,1)+1;
etable(i,4) = 2*nodes(i,2);
etable(i,5) = 2*nodes(i,2)+1;
etable(i,6) = 2*nodes(i,2)+2;
end

Upvotes: 0

Views: 99

Answers (1)

HansHirse
HansHirse

Reputation: 18925

You can use implicit expansion implicitly (introduced in MATLAB R2016b) or explicitly by using MATLAB's bsxfun to create that matrix:

% Parameters
EN = 10;
n = 6;
step = 3;

% Matrix (implict expansion, MATLAB >= R2016b)
etable = (0:step:EN*step-1).' + (1:n)

% Matrix (bsxfun, MATLAB < R2016b)
etable_legacy = bsxfun(@plus, (0:step:EN*step-1).', (1:n))

For the given parameter set, the outputs are:

etable =
    1    2    3    4    5    6
    4    5    6    7    8    9
    7    8    9   10   11   12
   10   11   12   13   14   15
   13   14   15   16   17   18
   16   17   18   19   20   21
   19   20   21   22   23   24
   22   23   24   25   26   27
   25   26   27   28   29   30
   28   29   30   31   32   33

etable_legacy =
    1    2    3    4    5    6
    4    5    6    7    8    9
    7    8    9   10   11   12
   10   11   12   13   14   15
   13   14   15   16   17   18
   16   17   18   19   20   21
   19   20   21   22   23   24
   22   23   24   25   26   27
   25   26   27   28   29   30
   28   29   30   31   32   33

You can change EN (number of rows), the "number of columns" n and/or the "step between rows" step.

Hope that helps.

Upvotes: 4

Related Questions