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

2 vues (au cours des 30 derniers jours)
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?

Réponse acceptée

Stephen23
Stephen23 le 29 Avr 2021
Modifié(e) : Stephen23 le 29 Avr 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/"

Plus de réponses (1)

Rik
Rik le 29 Avr 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 commentaires
SYML2nd
SYML2nd le 29 Avr 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 le 29 Avr 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by