How to write repeating string with variables in for loop
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Piet Jonker
el 5 de Abr. de 2019
Comentada: Piet Jonker
el 9 de Abr. de 2019
I'm trying to write a script for another program using MATLAB. I want to repeat these 7 lines 75 times, but after VideoA in line2 and after VideoA in line 4 I want number 1 to 75. I've tried the sprintf function, but can't get it to work. I hope this is clear, if not please ask! Can anybody help me?
line1 = ' new ScreenItem(ScreenVideoComponent,';
line2 = ' ''VideoA'',';
line3 = ' {';
line4 = ' video: ''assets/VideoA.mp4'',';
line5 = ' mime: ''video/mp4'',';
line6 = ' }';
line7 = ' ),';
1 comentario
Stephen23
el 5 de Abr. de 2019
"I've tried the sprintf function, but can't get it to work."
Please show us what you tried.
Respuesta aceptada
Dennis
el 5 de Abr. de 2019
Editada: Dennis
el 8 de Abr. de 2019
Check if this works for you.
for i=1:75
line1 = ' new ScreenItem(ScreenVideoComponent,';
line2 = sprintf(' VideoA%02d,',i);
line3 = ' {';
line4 = sprintf(' video: assets/VideoA%02d.mp4,',i);
line5 = ' mime: ','video/mp4'','; %i think this should be line5 = [' mime: ','video/mp4'','];
line6 = ' }';
line7 = ' ),';
end
Please notice that the above code overwrites all variables in each loop iteration. I also don't think that you need 7 different variables for your strings, you might want to have a look at Stephen's tutorial about dynamically named variables. Here is the slightly changed version of your code:
line=cell(7,75);
for i=1:75
line{1,i} = ' new ScreenItem(ScreenVideoComponent,';
line{2,i} = sprintf(' VideoA%02d,',i);
line{3,i} = ' {';
line{4,i} = sprintf(' video: assets/VideoA%02d.mp4,',i);
line{5,i} = [' mime: ','video/mp4'','] ;
line{6,i} = ' }';
line{7,i} = ' ),';
end
3 comentarios
Guillaume
el 5 de Abr. de 2019
@Dennis, I assume you meant to use %02d as a format (to generate 01, 02, ... 10, ... 75). %01d is the same as %d and generates 1,2, ...10, ... 75.
Más respuestas (1)
Guillaume
el 5 de Abr. de 2019
Editada: Guillaume
el 5 de Abr. de 2019
Well, if you really want uncluttered:
line = cell(7, 75);
line([1 3 5 6 7], :) = repmat({' new ScreenItem(ScreenVideoComponent,';
' {';
' mime: ''video/mp4'',';
' }';
' ),'}, 1, 75);
line(2, :) = compose(' VideoA%02d,',1:75);
line(4, :) = compose(' video: assets/VideoA%02d.mp4,', 1:75);
No need for a loop.
If all you want to do is just create a long string where the above is repeated 75 times, then:
lines = compose(strjoin({' new ScreenItem(ScreenVideoComponent,';
' ''VideoA%02d'',';
' {';
' video: ''assets/VideoA%02d.mp4'',';
' mime: ''video/mp4'',';
' }';
' ),'}, '\n'), ...
repelem(1:75, 2));
lines = strjoin(lines, '\n');
Ver también
Categorías
Más información sobre Numeric Types en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!