Create a loop with string
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I would like to create a loop command to read (i) file and, then, have all the curves on the same graph. I can minimize my case in the following example:
% with 1<(i)<100;
load TEXT_(i).txt;
x_(i) = TEXT_(i)(:,1);
y_(i) = TEXT_(i)(:,2);
z_(i) = TEXT_(i)(:,2);
XX_(i)=x_(i)+y_(i);
plot(XX_(i),z_(i));
0 comentarios
Respuestas (2)
KALYAN ACHARJYA
el 17 de Mzo. de 2018
Editada: KALYAN ACHARJYA
el 17 de Mzo. de 2018
% save all text files in a symmetric manner before doing the operation
% names for example text1,text2,text3...
%Save the folder of images in the current directory
path_directory='Folder_name'; % 'Folder name'
original_files=dir([path_directory '/*.txt']);
for i=1:length(original_files) *% if you want till 100 use "for i=1:100"*
filename=[path_directory '/' original_files(i).name];
load TEXT_(i).txt;
x_(i)=TEXT_(i)(:,1);
y_(i)=TEXT_(i)(:,2);
z_(i)=TEXT_(i)(:,2);
XX(i)=x_(i)+y_(i);
plot(XX_(i),z_(i));
hold on
end
3 comentarios
KALYAN ACHARJYA
el 18 de Mzo. de 2018
Editada: KALYAN ACHARJYA
el 18 de Mzo. de 2018
First, don't do any operation (till load file and check is there any error shows during run), just call one by one. Instead of calling from the desktop, keep the folder in Matlab current directory. try. Its perfectly work to call images in my case. I modified the code for text file.
Stephen23
el 19 de Mzo. de 2018
Editada: Stephen23
el 19 de Mzo. de 2018
Using command syntax with load is one of the main bugs in the code: as the MATLAB documentation describes the following text is interpreted as literal strings, not a variable that can be indexed into as you are attempting:
In general you should avoid using command syntax. Also it is recommended to always load into a variable rather than directly into the workspace, although in your case dlmread would probably be a better choice for reading the file. Use fullfile rather than string concatenation. It is often more efficient to load data first, before starting to process (e.g. plot) it. This should get you started (untested):
P = 'Folder_name';
D = dir(fullfile(P,'*.txt'));
C = cell(1,numel(D));
for k = 1:numel(D)
F = fullfile(P,S(k).name);
C{k} = dlmread(F);
end
A = cat(3,C{:}); % this lines assumes all matrices are the same size!
W = A(:,1,:)+A(:,2,:);
Z = A(:,3,:);
plot(W,Z)
If you want the files to be imported in the order of the numbers in their names then you will need to sort them: one possibility is to download and use my FEX submission natsortfiles.
0 comentarios
Ver también
Categorías
Más información sobre Characters and Strings 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!