How can I get multiple values from arrayfun?

2 visualizzazioni (ultimi 30 giorni)
I have the following sample code.
clear
clc
a = 1:1000;
b = linspace(100,200,1000);
x1 = arrayfun( @(v,w) fminsearch(@(x) (x(1)-v).^2 + (x(2)-w).^2, [1;1]), a, b, 'UniformOutput', false);
So basically, I would like to get x(1) x(2) that minimizes the objective function given a and b.
and x1 returns 1*1000 cells and each of the cells gives me the minimizer.
However, I want to get 21000 double instead of 11000 cells.
Is there any way I can get x1 as 2*1000?
Thanks in advance.

Risposta accettata

Stephen23
Stephen23 il 8 Nov 2021
Modificato: Stephen23 il 8 Nov 2021
"However, I want to get 21000 double instead of 11000 cells. Is there any way I can get x1 as 2*1000?"
Of course, just use a comma-separated list to concatenate the cell array contents together:
a = 1:1000;
b = linspace(100,200,1000);
fnh = @(v,w) fminsearch(@(x) (x(1)-v).^2 + (x(2)-w).^2, [1;1]);
x1 = arrayfun(fnh, a, b, 'UniformOutput', false);
x1 = [x1{:}] % comma-separated list
x1 = 2×1000
1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000 8.0000 9.0000 10.0000 11.0000 12.0000 13.0000 14.0000 15.0000 16.0000 17.0000 18.0000 19.0000 20.0000 21.0000 22.0000 23.0000 24.0000 25.0000 26.0000 27.0000 28.0000 29.0000 30.0000 100.0000 100.1001 100.2002 100.3003 100.4004 100.5005 100.6006 100.7007 100.8008 100.9009 101.0010 101.1011 101.2012 101.3013 101.4014 101.5015 101.6016 101.7017 101.8018 101.9019 102.0020 102.1021 102.2022 102.3023 102.4024 102.5025 102.6026 102.7027 102.8028 102.9029

Più risposte (2)

Yusuf Suer Erdem
Yusuf Suer Erdem il 8 Nov 2021
clear
clc
a = 1:1000;
b = linspace(100,200,1000);
x1 = arrayfun( @(v,w) fminsearch(@(x) (x(1)-v).^2 + (x(2)-w).^2, [1;1]), a, b, 'UniformOutput', false);
x2 = reshape(x1,2,500);
Try this way, as you see matrix x2 is the same matrix as x1 but in different dimensions. I hope it helps!

Walter Roberson
Walter Roberson il 8 Nov 2021
a = 1:1000;
b = linspace(100,200,1000);
x1 = cell2mat(arrayfun( @(v,w) fminsearch(@(x) (x(1)-v).^2 + (x(2)-w).^2, [1;1]), a, b, 'UniformOutput', false));
size(x1)
ans = 1×2
2 1000

Categorie

Scopri di più su Structures in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by