Hi, I am trying to write the following matlab code:
tic
for a=A
if (a==8)
disp('I found it');
break;
end
end
toc
but the moment I write tic in the command window it starts counting time, how can I tell matlab to start counting time only when the whole code in written?

 Accepted Answer

Ameer Hamza
Ameer Hamza on 17 Mar 2020
tic will restart the counter whenever you run it. So you don't need to worry if you ran tic several times before. Just run it after you have finished your code, and it will count from that point forward.

5 Comments

but I need it to count how much time my code take to run, can you provide working code?
The code you posted in question is a working example of using tic and toc. Are you pasting your code in the command window? Paste your code in a script file and press the run button in the "Editor" tab to run the code.
I discovered that way but I am looking for another solution in which I don't need to write my code in seperate file and pasting it again in the command window.
I would prefer to type my code in the command window and to wait untill I finish writing the whole code
MATLAB was specifically designed to write the testing code in a script file, and the command line is only to run a maximum of 1-2 lines of code. You can still do it, by not pressing enter after each line of code. Just press shift + enter to move to the next line. When you reach the end of the code, you can press enter to run the code.
For example, type like this
tic % [press shift + enter]
x = rand(100); % [press shift + enter]
y = rand(100); % [press shift + enter]
z = x + y; % [press shift + enter]
toc % [press enter]
Thanks!

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!