I would like to compile a text string for each one of the three index of two given arrays

1 visualización (últimos 30 días)
Hi,
Given two array XX=[1,2,3] YY=[3,2,1]
and a typical string:
&DEVC ID='vel_XX', QUANTITY='VELOCITY', ABC=YY,0.0525,9.74/
where the bold letters represent the given array. I would like to write a string for each one of the three index of the arrays:
&DEVC ID='vel_1', QUANTITY='VELOCITY', ABC=3,0.0525,9.74/
&DEVC ID='vel_2', QUANTITY='VELOCITY', ABC=2,0.0525,9.74/
&DEVC ID='vel_3', QUANTITY='VELOCITY', ABC=1,0.0525,9.74/
Can You Help me?

Respuesta aceptada

Stephen23
Stephen23 el 29 de Abr. de 2021
Editada: Stephen23 el 29 de Abr. de 2021
Simpler with compose:
XX = [1,2,3,4.96875];
YY = [3,2,1,0];
fmt = "&DEVC ID=''vel_%g'', QUANTITY=''VELOCITY'', ABC=%d,0.0525,9.74/";
out = compose(fmt,XX(:),YY(:))
out = 4×1 string array
"&DEVC ID=''vel_1'', QUANTITY=''VELOCITY'', ABC=3,0.0525,9.74/" "&DEVC ID=''vel_2'', QUANTITY=''VELOCITY'', ABC=2,0.0525,9.74/" "&DEVC ID=''vel_3'', QUANTITY=''VELOCITY'', ABC=1,0.0525,9.74/" "&DEVC ID=''vel_4.96875'', QUANTITY=''VELOCITY'', ABC=0,0.0525,9.74/"

Más respuestas (1)

Rik
Rik el 29 de Abr. de 2021
Easy with sprintf:
XX=[1,2,3];
YY=[3,2,1];
z=repmat("",size(XX));
FormatSpec='&DEVC ID=''vel_%d'', QUANTITY=''VELOCITY'', ABC=%d,0.0525,9.74/';
for n=1:numel(XX)
z(n)=string(sprintf(FormatSpec,XX(n),YY(n)));
end
disp(z.')
"&DEVC ID='vel_1', QUANTITY='VELOCITY', ABC=3,0.0525,9.74/" "&DEVC ID='vel_2', QUANTITY='VELOCITY', ABC=2,0.0525,9.74/" "&DEVC ID='vel_3', QUANTITY='VELOCITY', ABC=1,0.0525,9.74/"
  2 comentarios
SYML2nd
SYML2nd el 29 de Abr. de 2021
Thank you, I used your code. The only problem is that I don't want the scientific format of the numbers like that:
"&DEVC ID='Y_u_vel_-4.968750e+00', QUANTITY='U-VELOCITY', XYZ=4.99,2.125000e-02,9.74/"
I would like to have:
"&DEVC ID='Y_u_vel_-4.96875', QUANTITY='U-VELOCITY', XYZ=4.99,0.2125,9.74/"
How can I obtain that?
Rik
Rik el 29 de Abr. de 2021
For completeness' sake: you should read the documentation for sprintf (or fprintf), which will show you the full list of options, including the %g flag that Stephen used in his answer.

Iniciar sesión para comentar.

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by