How to read '.m' files which is already saved in matlab
50 ビュー (過去 30 日間)
古いコメントを表示
I am just find the year by year nanmaean and saved that script by creating a new folder.Now i want to plot polynomial curve fitting using these nanmean values corresponding to the years .But i couldn't read that all seperate scripts together to plot that . For this am just used the following code, only showing the number of files. Folder= path upto new folder , File= dir('*.m')
4 件のコメント
Stephen23
2023 年 6 月 20 日
編集済み: Stephen23
2023 年 6 月 20 日
"How to read '.m' files which is already saved in matlab"
Note that:
- .M files store code, and can be run (scripts) or called/evaluated (functions).
- .MAT file store data, and the data can be imported.
Are you really storing data in .M files? Or are they scripts for running? Your question does not make this clear.
回答 (2 件)
Diwakar Diwakar
2023 年 6 月 19 日
If you will provide the .m file then we can able to give you the propoer answer with code. meanwile try the below code. may be it will help you.
% Step 1: Create a folder to store the '.m' files
% Step 2: Save each script as a separate '.m' file in the folder
% Step 3: Read the '.m' files
folder = 'path_to_folder'; % Replace 'path_to_folder' with the actual path to your folder
files = dir(fullfile(folder, '*.m'));
% Step 4: Loop through each file and calculate the nanmean values
nanmeans = [];
for i = 1:length(files)
file = fullfile(folder, files(i).name);
run(file); % Execute the script
nanmeans = [nanmeans, nanmean]; % Store the nanmean value
end
% Step 5: Plot the polynomial curve fitting
years = 1:length(nanmeans); % Assuming each script corresponds to one year
degree = 2; % Set the degree of the polynomial curve fitting
coefficients = polyfit(years, nanmeans, degree);
curve = polyval(coefficients, years);
plot(years, nanmeans, 'o', years, curve);
xlabel('Year');
ylabel('nanmean');
title('Polynomial Curve Fitting');
legend('Data Points', 'Curve Fitting');
2 件のコメント
Stephen23
2023 年 6 月 20 日
Do not use the variable name NANMEAN, because this shadows the inbuilt function of the same name.
Sarthak
2023 年 6 月 19 日
Hello Jincy,
What I understand from your question is that you want to plot the data from separate MATLAB files on a single plot. For that, you can add the required MATLAB files to the MATLAB Search Path and then use them to plot the curve. You can add a folder containing the files to the MATLAB path by:
- Right click on the folder.
- Click on ‘Add to Path’.
You can also use the ‘addpath’ function in MATLAB to add your files/folders to the MATLAB search path, the link of whose documentation is attached below:
Once you add the files to the path, you can simply load the files where you want to plot them by using load(‘fileName.m’).
Hope this helps!!
参考
カテゴリ
Help Center および File Exchange で Startup and Shutdown についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!