How can I reuse numerical values them back as inputs?

1 次查看(过去 30 天)
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

回答(2 个)

Sarthak
Sarthak 2023-2-20
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 2023-2-20
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 + .

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT-Files 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by