3 ms·
Or, you could just write: M = repmat(f(1:10), n, 1); where 'n' gives the number of rows you want in 'M' and 'f' is written in proper "Matlab" style (i.e.
by psb217 14y ago
Or, you could just write:
M = repmat(f(1:10), n, 1);
where 'n' gives the number of rows you want in 'M' and 'f' is written in proper "Matlab" style (i.e. behaves reasonably when given an array as input). Or, to be more in the spirit of linear algebra, you could write:
M = ones(n,1) * f(1:10);
And, if you only want one row-wise copy, you could (succinctly) write:
M = f(1:10);
Or, as you suggested, you could write something like:
M = repmat(arrayfun(@(x)f(x), 1:10), n, 1);
Or, getting more silly, and using the handy bsxfun, you could write:
M = bsxfun(@times, ones(n,10), f(1:10));
If you don't feel like implementing 'f' so as to permit array inputs, you could modify this to:
M = bsxfun(@times, ones(n,10), arrayfun(@(x)f(x), 1:10));
Anyhow, Matlab is very productive if you can effectively wield its powerful built-ins.
- mbq 14y agoYou didn't get my example -- it was about how to make a matrix from the results of a non-vectorised function that gets one number and returns a vector (say performs a complex simulation). The problem you've solved has an equally simple implementations in R; f(1:10) for a single copy, matrix(f(1:10),10,n) for n columns, matrix(f(1:10),n,10,byrow=T) for n rows, etc.