Azzera filtri
Azzera filtri

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

11 visualizzazioni (ultimi 30 giorni)
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:
for ii=1:nxx
Thanks in advance!

Risposta accettata

Tommy il 26 Giu 2020
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 Commenti
Ulrich Becker
Ulrich Becker il 26 Giu 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!

Accedi per commentare.

Più risposte (1)

Ulrich Becker
Ulrich Becker il 26 Giu 2020
Modificato: Ulrich Becker il 26 Giu 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 Commento
Tommy il 27 Giu 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

Accedi per commentare.


Scopri di più su Loops and Conditional Statements in Help Center e File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by