I have a txt. file used in a function. I need a variable in the txt. file to cycle through different values (for loop), and the function needs to run for each value.

60 views (last 30 days)
I can't figure out how to make a specific variable in a txt file to change, and for the function to even run when the file itsn't just the right numbers. I tried just making a new text file for each step, but that is way too many files for one problem.
txt. file:
8
1 0 0
2 10 10*tan(theta)
3 10 0 4 20 10*tan(theta)
5 20 0 6 30 10*tan(theta)
the above values are in a text file and each number is used to calculate a final product via a seperate function script. It doesn't run with equations there, so I was thinking of replacing 10*tan(theta) with a variable. It needs to run from theta =20-80 in increments of 5. Please help however you can.

Answers (2)

Madheswaran
Madheswaran on 20 Nov 2024 at 3:12
Edited: Madheswaran on 20 Nov 2024 at 4:28
You can read and evaluate the text file, without modifying/cleating a new text file with the following approach. The function, 'readInputWithExpr' takes filename and theta value as argument, and returns the evaluated data in a array of cells.
function result = readInputWithExpr(filename, theta)
lines = readlines(filename);
result = cell(length(lines), 1);
for i = 1:length(lines)
% Split the line by spaces
parts = split(lines(i));
lineResult = [];
% Process each part
for j = 1:length(parts)
if contains(parts(j), 'theta')
% If part contains 'theta', evaluate the expression
expr = replace(parts(j), 'theta', num2str(theta));
val = eval(expr);
lineResult = [lineResult, val];
else
% If part is a number, convert to double
val = str2double(parts(j));
lineResult = [lineResult, val];
end
end
result{i} = lineResult;
end
end
% Now you can call the 'readInputWithExpr' function inside a loop
for theta = 20:5:30 % Change to 20:5:80
data = readInputWithExpr('input.txt', theta);
fprintf('When theta = %.f', theta)
disp(data)
% process data here
end
When theta = 20
{[ 8]} {[ 1 0 0]} {[ 2 10 22.3716]} {[3 10 0 4 20 22.3716]} {[5 20 0 6 30 22.3716]}
When theta = 25
{[ 8]} {[ 1 0 0]} {[ 2 10 -1.3353]} {[3 10 0 4 20 -1.3353]} {[5 20 0 6 30 -1.3353]}
When theta = 30
{[ 8]} {[ 1 0 0]} {[ 2 10 -64.0533]} {[3 10 0 4 20 -64.0533]} {[5 20 0 6 30 -64.0533]}
In the above 'for loop', I have used the theta values '20:5:30' just to display first 3 sample outputs, you can change it to '20:5:80' as you required. Also, note that above approach uses 'eval' function, use the 'eval' function only if you are certain about the data in the text file.
For more information, refer to the following documentations:
  1. https://mathworks.com/help/matlab/ref/eval.html
  2. https://mathworks.com/help/matlab/ref/str2double.html
Hope this works for you!

Umar
Umar on 20 Nov 2024 at 3:34

Hi @Cornelia,

I created a MATLAB script that reads the data from a text file, replaces the specified expression with a variable, and iterates through a range of values for that variable. Finally, output the results to a new text file. Below are the detailed steps and the complete code.

Step 1: Create the Initial Text File

First, create a text file that contains your initial data. You can do this directly in MATLAB using the following code:

% Create a text file with initial data
fileID = fopen('data.txt', 'w');
fprintf(fileID, '8\n');
fprintf(fileID, '1 0 0\n');
fprintf(fileID, '2 10 10*tan(theta)\n');
fprintf(fileID, '3 10 0 4 20 10*tan(theta)\n');
fprintf(fileID, '5 20 0 6 30 10*tan(theta)\n');
fclose(fileID);

Step 2: Read and Modify the Text File

Next, read the contents of the text file, replace the expression 10*tan(theta) with a variable, and prepare for calculations. The following code snippet demonstrates how to achieve this:

% Read the data from the text file
fileID = fopen('data.txt', 'r');
data = textscan(fileID, '%s', 'Delimiter', '\n');
fclose(fileID);
% Replace '10*tan(theta)' with a variable 'var'
theta_values = 20:5:80; % Range of theta values
results = []; % Initialize results array
for theta = theta_values
  % Create a new variable for the current theta value
  var = 10 * tand(theta); % Use tand for degrees
  modified_data = strrep(data{1}, '10*tan(theta)', num2str(var));
    % Display modified data for verification
    disp('Modified Data:');
    disp(modified_data);
    % Perform calculations based on modified data
    % Here, you can implement your specific calculations
    % For demonstration, we will just sum the values
    current_result = 0;
    for i = 1:length(modified_data)
        numbers = sscanf(modified_data{i}, '%f');
        current_result = current_result + sum(numbers);
    end
    results = [results; theta, current_result]; % Store results
  end

Step 3: Output the Results to a New Text File

Finally, write the results to a new text file for further analysis:

% Write results to a new text file
outputFileID = fopen('results.txt', 'w');
fprintf(outputFileID, 'Theta\tResult\n');
for i = 1:size(results, 1)
  fprintf(outputFileID, '%d\t%.2f\n', results(i, 1), results(i, 2));
end
fclose(outputFileID);

Please see attached.

My final notes:

Adjust the calculations in the loop as per your specific requirements.

The use of tand is crucial here since it computes the tangent of an angle in degrees.

By following these steps, you should be able to modify the variable in your text file and run your calculations efficiently without creating multiple files.

Hope this helps.

If you have any further questions or need additional modifications, feel free to ask!

Community Treasure Hunt

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

Start Hunting!