# How to fill a matrix column by column better than by a for loop?

2 views (last 30 days)
Ulrich Becker on 26 Jun 2020
Commented: Tommy on 27 Jun 2020
Want to parametrize areas for plotting/numerical integration/whatnot.
E.g. x-values: 0..1
y-values: x-1 ... x^3+1
This does the job, but it is awful:
xx=0:0.1:1;
nxx=length(xx);
nyy=10;
xm=repmat(xx',1,nyy);
ym=zeros(nxx,nyy);
for ii=1:nxx
xii=xx(ii);
ym(ii,:)=linspace(xii-1,xii^3+1,nyy);
end

Tommy on 26 Jun 2020
xx = 0:0.1:1;
nxx = numel(xx);
nyy = 10;
xm = repmat(xx',1,nyy);
base = linspace(0,1,nyy);
starts = xx-1;
stops = xx.^3+1;
ym = starts(:) + base.*(stops(:)-starts(:));

Ulrich Becker on 26 Jun 2020
The answer is a massive improvement in performance and logic! Thanks indeed for this quickest reply!
I wonder if one could condense it even further, so I'd like to leave this question open a little longer. In particular, as the issue has wider applicability, as your reference is indicating.
Again, thanks ideed!
Tommy on 26 Jun 2020
Happy to help!

Ulrich Becker on 26 Jun 2020
Edited: Ulrich Becker on 26 Jun 2020
Taking the ideas of the accepted answer, I learned more about rows and columns and since this forum is about learning, here is a more homogeneous/symmetric version:
nxx = 15; % number of points in x direction
nyy = 11; % number of points in y direction
x1=0; x2=1; % start and end value for x-values
xx = linspace(x1,x2,nxx)'; % Want a column vector! Length is first matrix dimension: number of rows.
yy = linspace(0,1,nyy); % Want a row vector! Length is second matrix dimension: number of columns.
y1 = xx-1; % Column vector. Start values of y depending on x.
y2 = xx.^3+1; % Column vector. End values of y depending on x.
xm = repmat(xx,1,nyy); % xx needs to be a column vector for this to work.
ym = y1 + yy.*(y2-y1); % Need columns and rows for this to give a matrix!
Also note:
a=[1 2 3] % is a row vector
a' % is a column vector ... no surprise
a(:) % is a column vector, too! Well, it's in the documentation. So no surprise ... anymore.
Again, thanks for the accepted answer!

#### 1 Comment

Tommy on 27 Jun 2020
Nice and neat, thanks for this! In case anyone reading isn't already aware:
a=[1;2;3] % is a column vector
a(:) % is still a column vector