Matlab中基于choose_pol变量动态创建不同名称TXT文件及读取需求
Got it, let's break this down into two straightforward parts: creating files with variable-dependent names, then reading them back later in another script.
Saving Files with choose_pol-Based Names
The core here is generating a dynamic filename that ties directly to your choose_pol variable. MATLAB's sprintf function is perfect for this—it lets you easily insert numeric values into string filenames.
Generate the dynamic filename:
% Example: If choose_pol is 3, this creates "theta_pol_3.txt" filename = sprintf('theta_pol_%d.txt', choose_pol);If you want to save files to a specific folder (keeps things organized!), add a directory path (just make sure the folder exists first):
% Create output folder if it doesn't exist save_dir = 'polarization_results'; if ~exist(save_dir, 'dir') mkdir(save_dir); end % Build full path to the file filename = fullfile(save_dir, sprintf('theta_pol_%d.txt', choose_pol));Save your
THETAmatrix withdlmwrite:
Use the generated filename to save your matrix. You can specify a delimiter (like commas) if you need CSV-style files:% Basic save with default tab delimiter dlmwrite(filename, THETA); % Or save with comma-separated values dlmwrite(filename, THETA, 'delimiter', ',');
Reading the Files Later
When loading these files in another script, you have two common approaches depending on what you know about the choose_pol values.
Option 1: You know the range of choose_pol values (e.g., 1 to 5)
Loop through the values, generate the same filenames as when saving, and read each matrix:
% Define the range of choose_pol values you used pol_range = 1:5; for pol = pol_range % Generate the exact filename from earlier filename = sprintf('theta_pol_%d.txt', pol); % Use the full path if you saved to a folder: % filename = fullfile('polarization_results', sprintf('theta_pol_%d.txt', pol)); % Read the matrix THETA_read = dlmread(filename); % Do something with THETA_read here (e.g., analyze, plot, store in a cell array) end
Option 2: You don't know the exact choose_pol values
Use dir to find all matching files in the directory, then extract the choose_pol value directly from the filename:
% Find all files matching the pattern "theta_pol_*.txt" file_list = dir('theta_pol_*.txt'); % Use the folder path if needed: dir(fullfile('polarization_results', 'theta_pol_*.txt')) for k = 1:length(file_list) filename = file_list(k).name; % Read the matrix THETA_read = dlmread(filename); % Extract the choose_pol value from the filename [~, name_no_ext, ~] = fileparts(filename); pol_str = strrep(name_no_ext, 'theta_pol_', ''); choose_pol = str2double(pol_str); % Now you have both the matrix and its corresponding choose_pol value fprintf('Loaded data for choose_pol = %d\n', choose_pol); end
内容的提问来源于stack exchange,提问作者Shika93

