Constructing a string with several index requirements
Afficher commentaires plus anciens
Hello, I have a vector of numbers r2 that I need to send over a communciation to an array (called ScanArray). The comms is such that I can only send upto 50 elements in each send (Im using writeline)
Heres the 1st 8 values I need to send
r2 =
0 30 60 90 120 150 180 210
and heres my string that I construct that I send with writeline function
command=['ScanArray(0)(0)=',num2str(r2(1,1)),'ScanArray(0)(1)=',num2str(r2(1,2)),'ScanArray(0)(2)=',num2str(r2(1,3)),'ScanArray(0)(3)=',num2str(r2(1,4))]
Rather than write this out for 50 elements ScanArray(0)(0) -> ScanArray(0)(49), is there a more effcient way to construct this. This was my attemp:
command=[];
for i=1:50
commandnew=['ScanArray(0)(',num2str(i),')=',num2str(r2(1,i))]
command=[command,commandnew]
end
2 commentaires
"is there a more effcient way to construct this."
Do not fight MATLAB with loops. Use e.g. strings or COMPOSE:
r2 = 0:30:210;
ix = 1:numel(r2);
tx = "ScanArray(0)(" + ix(:) + ")=" + r2(:)
tx = compose('ScanArray(0)(%u) = %u',ix(:),r2(:))
r2 = 0:30:210;
ix = 0:numel(r2)-1;
tx = "ScanArray(0)(" + ix(:) + ")=" + r2(:);
tx = [tx{:}]
tx = compose('ScanArray(0)(%u)=%u',ix(:),r2(:));
tx = [tx{:}]
Réponse acceptée
Plus de réponses (3)
r2 = [0 30 60 90 120 150 180 210];
command = sprintf('ScanArray(0)(%d)=%g',[0:numel(r2)-1; r2])
The %g is to handle cases where elements of r2 are not integers. If they are always integers you can use %d there instead.
And I don't know but you may need a delimiter between adjacent ScanArray(0) assignments, as in
command = sprintf('ScanArray(0)(%d)=%g ',[0:numel(r2)-1; r2])
or
command = sprintf('ScanArray(0)(%d)=%g;',[0:numel(r2)-1; r2])
etc.
r2 = [0 30 60 90 120 150 180 210];
ind = 0:numel(r2)-1;
result = join("ScanArray(0)(" + ind + ")=" + r2, newline)
Replace newline with ";" to join the substrings with semicolons rather than newlines (which I used so you can easily see the individual substrings included in result.)
4 commentaires
r2 = (0:47)*30;
N = numel(r2);
n = 4;
assert(mod(N,n) == 0)
[idx1,idx2] = meshgrid(0:N/n-1,0:n-1)
result = join("ScanArray("+idx1(:)+")("+idx2(:)+")="+r2(:),newline())
Or:
r2 = (0:47)*30;
N = numel(r2);
n = 4;
assert(mod(N,n) == 0)
result = strjoin("ScanArray("+(0:N/n-1)+")("+(0:n-1).'+")="+reshape(r2,n,[]),newline())
Jason
le 10 Nov 2024
4 commentaires
Thst should work essentially as you wrote it.
The only change I made here is to enclose the arithmetic operation in parentheses —
jx = 1:4
ix = 0:3
tx(jx,:) = "ScanArray("+(jx(:)-1)+")(" + ix(:) + ")="
.
Jason
le 11 Nov 2024
jx = 1:4;
ix = 0:3;
tx = "ScanArray("+(jx-1)+")("+ix(:)+")=";
tx = tx(:)
Jason
le 11 Nov 2024
Catégories
En savoir plus sur String dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
