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

18 次查看(过去 30 天)
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
Thanks in advance!

采纳的回答

Tommy
Tommy 2020-6-26
How about something like this?
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(:));
Credit to the following answer:
  2 个评论
Ulrich Becker
Ulrich Becker 2020-6-26
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!

请先登录,再进行评论。

更多回答(1 个)

Ulrich Becker
Ulrich Becker 2020-6-26
编辑:Ulrich Becker 2020-6-26
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 个评论
Tommy
Tommy 2020-6-27
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by