How can I reuse numerical values them back as inputs?

1 view (last 30 days)
If I let x=1 in the Command Window, and I run the script:
clc
x=x+1
I would get x=1, then x=2, then x=3, and so on as long as I rerun the script. Is there a way to do this in my script only without having to put x=1 in the Command Window? I'm hope to avoid using functions and function handles if possible.
Thanks in advance! :D

Answers (2)

Sarthak
Sarthak on 20 Feb 2023
Hi,
You can save it to a MAT-file and then load it back in before the script runs. This way, each time the script is run, it will load the current value of x from the MAT-file, increment it, and save it back to the MAT-file for the next run.
Please refer to the following code:
save('x.mat', 'x');
clc
load('x.mat');
x = x + 1;
save('x.mat', 'x');

Jan
Jan on 20 Feb 2023
Working with functions is the way to go. You cannot use Matlab efficiently without functions.
But as far as I understand, your problem can be solved with out using a self-written function:
% Script: yourScript.m
if ~exist('x', 'var')
x = 0;
end
x = x + 1
Starting this script will create x automatically, if it does not exist before. Of course, exist() is a function, but other functions are called also for the operators = and + .

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!