adding strings per component

Hi,
I have the following code:
for n = 1:4
velocity = ['v_',num2str(n),' = n*2'];
eval(velocity)
position = ['x_', num2str(n), '= n.^2'];
eval(position)
end
So, the expected output would be: v_1 = 2, x_1 = 1 \\ v_2 = 4, x_2 = 4 \\ … \\ v_4 = 8, x_4 = 16.
Let's say we want to do something to the components. For example, add v_1 + x_1, (we want to do something to variables with the same index.) How do we do that?

 Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 29 de Nov. de 2014

0 votos

6 comentarios

cgo
cgo el 29 de Nov. de 2014
Hello, I am lost. Please elaborate. What could be a better alternative/solution to the problem above?
Thanks
Azzi Abdelmalek
Azzi Abdelmalek el 29 de Nov. de 2014
Editada: Azzi Abdelmalek el 29 de Nov. de 2014
The alternative is to work with arrays, or cell arrays. In your case:
s(:,1)=(1:4)'*2
s(:,2)=(1:4)'.^2
The first column represent the velocity and the second represent the position. Why to create a name for each value when you can use just one? Then if you want to sum velocity and position
out=sum(s,2)
cgo
cgo el 29 de Nov. de 2014
This is neater and elegant. Thank you.
per isakson
per isakson el 29 de Nov. de 2014
... or two structures called, e.g.&nbsp velocitiy &nbspand&nbsp position
for n = 1:4
velocity.( sprintf('v_%d', n ) ) = n*2;
position.( sprintf('x_%d', n ) ) = n.^2;
end
This is a good alternative when the names of the fields carry valuable information on the code, but maybe not this time.
You can also use table
velocity=s(:,1);
position=s(:,2);
out=table(velocity,position)
cgo
cgo el 29 de Nov. de 2014
Thanks again.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

cgo
el 29 de Nov. de 2014

Comentada:

cgo
el 29 de Nov. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by