Effacer les filtres
Effacer les filtres

How to set the name with num2str in for loop?

5 vues (au cours des 30 derniers jours)
Sopo Yoon
Sopo Yoon le 21 Oct 2022
Commenté : Stephen23 le 22 Oct 2022
Hi!
I run the c code and have a number of .dat file.
% cp_1.dat, cp_2.dat and so on.
I want to import and make some results using them.
But I'm not able to use it.
My code is below:
for k = 1:1000
load(['cp_',num2str(k),'.dat']);
A = ['cp_',num2str(k)]; %%%%%%%%%%%% The problem!!!
if k==1
B = zeros(size(A));
end
% This loop shifts the array.
for i = 1:7
ii = abs(i-8);
A(i+14,:) = A(ii,:);
A(i+21,:) = A(ii,:);
end
A(length(a)+1,:) = A(1,:);
B(:,:) = B(:,:)+A(:,:)
end
I hope you understand my aim.
Best,
Sopo
  3 commentaires
Sopo Yoon
Sopo Yoon le 22 Oct 2022
When I use a command 'readmatrix' instead of 'load', I get a error :
Undefined function or variable 'readmatrix'.
Error in Cp (line 14)
A = readmatrix(F);
Stephen23
Stephen23 le 22 Oct 2022
"When I use a command 'readmatrix' instead of 'load', I get a error"
Because you did not fill out the Release field it is assumed that you have a recent release. But apparently you do not.
Try using DLMREAD or CSVREAD or whatever your installed MATLAB version supports.

Connectez-vous pour commenter.

Réponse acceptée

Bjorn Gustavsson
Bjorn Gustavsson le 21 Oct 2022
Perhaps it is as simple as:
for k = 1:1000
% assign the content of the file directly to variable A:
A = load(['cp_',num2str(k),'.dat']);
if k==1
B = zeros(size(A));
end
% This loop shifts the array.
for i = 1:7
ii = abs(i-8);
A(i+14,:) = A(ii,:);
A(i+21,:) = A(ii,:);
end
A(length(a)+1,:) = A(1,:);
B(:,:) = B(:,:)+A(:,:)
end
This will obviously rely on the files containing similar enough data, but that would have applied even for your solution.
HTH
  1 commentaire
Sopo Yoon
Sopo Yoon le 22 Oct 2022
Thanks to you, I can use a right variable.
Best,
Sopo

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by