MATLAB 顯示字串

Ammar Ali 2023年1月30日
  1. 在 MATLAB 中使用 disp() 函式顯示字串
  2. 在 MATLAB 中使用 disp() 函式顯示字串
MATLAB 顯示字串

本教程將介紹如何使用 disp()sprintf() 函式在 MATLAB 中顯示字串。

在 MATLAB 中使用 disp() 函式顯示字串

你可以使用 disp() 函式在 MATLAB 中顯示字串。例如,讓我們顯示一個包含字串的變數。請參見下面的程式碼。

str = "Hello World";
disp(str)

輸出:

Hello World

在上面的程式碼中,我們顯示一個包含字串的變數 str。我們還可以將多個字串連線到陣列中,並使用 disp() 函式顯示它們。請參見下面的程式碼。

name = 'Sam';
age = 25;
str = [name, ' is ', num2str(age), ' years old.'];
disp(str)

輸出:

Sam is 25 years old.

確保將每個變數都更改為 char,以避免錯誤。

在 MATLAB 中使用 disp() 函式顯示字串

你可以使用 sprintf() 函式在 MATLAB 中顯示字串。例如,讓我們在 MATLAB 中顯示一個包含字串的變數。請參見下面的程式碼。

str = "Hello World";
sprintf("%s",str)

輸出:

ans = 

    "Hello World"

我們可以設定變數的格式,然後使用 sprintf() 函式來顯示它,就像 C 語言中的 fprintf() 一樣。例如,讓我們使用 sprintf() 函式格式化浮點數。請參見下面的程式碼。

f = 1.1234;
sprintf("%0.2f",f)

輸出:

ans = 

    "1.12"

在上面的程式碼中,我們顯示一個浮點數,最多兩位小數。

作者: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

相關文章 - MATLAB String