在 Matlab 的命令列視窗中列印輸出

Sheeraz Gul 2023年1月30日
  1. 在 Matlab 的命令列視窗中使用 disp() 方法列印輸出
  2. 在 Matlab 的命令列視窗中使用 fprintf() 方法列印輸出
在 Matlab 的命令列視窗中列印輸出

本教程演示如何使用 Matlab 在命令視窗中列印輸出。

在 Matlab 的命令視窗中有多種列印輸出的方法。我們可以使用 fprintf()disp() 方法。

在 Matlab 的命令列視窗中使用 disp() 方法列印輸出

disp() 方法在 Matlab 中顯示變數的值。例如,disp(a) 將顯示變數 a 的值而不顯示變數名。

如果要顯示帶有名稱的變數的值,可以先顯示 a =,然後顯示變數。

disp() 方法可以顯示任何變數。如果變數(如陣列)為空,則 disp() 將不會列印任何內容。

例子:

A = [5 10 15
     20 25 30
     35 40 45 ];
B = 'Hello! This is Delftstack.com';
C = 100;

disp('A = ')
disp(A)

disp('B = ')
disp(B)

disp('C = ')
disp(C)

上面的程式碼將顯示變數 A(陣列)、B(字串)和 C(整數)的值。

輸出:

>> matlabprintcommand
A = 
     5    10    15
    20    25    30
    35    40    45

B = 
Hello! This is Delftstack.com
C = 
   100

在 Matlab 的命令列視窗中使用 fprintf() 方法列印輸出

Matlab 中的 fprintf() 方法以特定格式列印命令視窗中的值。例如,fprintf(fileID,formatSpec,A1,...,An) 會將 formatSpec 應用到從 A1An 的陣列中的所有元素(按列順序)。

它還將使用 fileID 將資料寫入文字檔案。

例子:

A1 = 'Jack';
A2 = 'John';
A3 = 'Mike'; 
A4 = 'Michelle';
formatSpec = 'The employee name is %s\n'; 
fprintf(formatSpec, A1, A2, A3, A4);

上面的程式碼將根據給定的格式規範顯示值。

輸出:

>> matlabprintcommand
The employee name is Jack
The employee name is John
The employee name is Mike
The employee name is Michelle
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook