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

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 日

1 投票

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!
Tommy
Tommy 2020 年 6 月 26 日
Happy to help!

サインインしてコメントする。

その他の回答 (1 件)

Ulrich Becker
Ulrich Becker 2020 年 6 月 26 日
編集済み: Ulrich Becker 2020 年 6 月 26 日

0 投票

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

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

質問済み:

2020 年 6 月 26 日

コメント済み:

2020 年 6 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by