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

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Stephen23
Stephen23 il 29 Apr 2021
Modificato: Stephen23 il 29 Apr 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/"

Più risposte (1)

Rik
Rik il 29 Apr 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 Commenti
SYML2nd
SYML2nd il 29 Apr 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 il 29 Apr 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.

Accedi per commentare.

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by