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

2 次查看(过去 30 天)
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?

采纳的回答

Stephen23
Stephen23 2021-4-29
编辑:Stephen23 2021-4-29
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/"

更多回答(1 个)

Rik
Rik 2021-4-29
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 个评论
SYML2nd
SYML2nd 2021-4-29
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 2021-4-29
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by