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

조회 수: 9 (최근 30일)
Ulrich Becker
Ulrich Becker 2020년 6월 26일
댓글: Tommy 2020년 6월 27일
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에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by