Is it possible to copy the elements of a matrix to a set of variable names ?

Given is a matrix A of size [1x6]. What I want is to copy the elements of A to a set of variable names [a,b,c,d,e,f], so that
a = A(1);
b= A(2)
a.s.o.
I tried
[a,b,c,d,e,f] = deal(A);
But this copies not the elements but the hole matrix A into each variable.
Any help is much appreciated.

 Respuesta aceptada

Walter Roberson
Walter Roberson el 13 de Mzo. de 2013
Editada: Walter Roberson el 13 de Mzo. de 2013
Acell = num2cell(A);
[a,b,c,d,e,f] = deal(Acell{:}); %older MATLAB
[a,b,c,d,e,f] = Acell{:}; %newer MATLAB

1 comentario

Thanks Walter. This is quite simple. And I do not have any problems with definition of what workspace it is.
Thank you, Azzi for your help too.

Iniciar sesión para comentar.

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 13 de Mzo. de 2013
Editada: Azzi Abdelmalek el 13 de Mzo. de 2013
A=rand(1,6)
s='abcdef'
for k=1:numel(s)
assignin('base',s(k),A(k))
end

6 comentarios

Thanks Azzi.
What I ment was, is there a single function, as for instance deal, to avoid a for-loop?
A=rand(1,6)
s='abcdef'
arrayfun(@(x) assignin('base',s(x),A(x)),1:numel(s))
%or
arrayfun(@(x,y) assignin('base',x,y),'a':'f',A)
Ok, this work fine. Thanks.
Now I have one additional problem with the workspace definition. I have put this code into a function. And neighter 'base' nor 'caller' produces the variables in the function workspace but in the base workspace. So calling the function produces an error.
Post your function
% generates function handle to bimodal gaussian distribution:
% f(X; A1, A2, x01, x02, sig1, sig2) = ...
% A1*exp( -(X-x01).^2 / (2*sig1^2) ) + A2*exp( -(X-x02).^2 / (2*sig2^2) )
% beta is the coefficient vector [A1,A2,x01,x02,sig1,sig2]
function f = bimodgauss(beta)
s={'A1','A2','x01','x02','sig1','sig2'};
for k=1:numel(s)
assignin('caller',s{k},beta(k))
end
f = @(X) A1*exp(-(X-x01).^2 / (2*sig1^2)) + A2*exp(-(X-x02).^2 / (2*sig2^2));

Iniciar sesión para comentar.

Categorías

Más información sobre Eigenvalues & Eigenvectors en Centro de ayuda y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by