# MATLAB

MATLAB constructs like [parfor ](https://www.mathworks.com/help/parallel-computing/parfor.html)can be leveraged in applications using local [parallel pools](https://www.mathworks.com/help/parallel-computing/parpool.html).\
Nuvolos will configure MATLAB to use the appropriate number of CPUs automatically, so you can start your parpool with the command:

```
pp = parpool('local');
```

The pool will be deleted after 30 minutes of idle time or with an application restart. To delete it manually, use

```
pp.delete()
```

### Issue with starting the parallel pool

You might have encountered lately the following error message in MATLAB on Nuvolos when starting a new parallel pool:

> Mismatch between number of environment names and values

This is due to a recent change by MathWorks regarding the online login process. The workaround is to issue the following command in the MATLAB terminal:

```
parallel.internal.mwa.ensureLoggedIn()
```

This will open up a dialog where you need to enter again your MathWorks credentials. After that, MATLAB will be able to start the parallel pool.

{% hint style="info" %}
You might not see a blinking cursor in the textbox for your credentials in the popup, but you can still type there.
{% endhint %}

## Using OpenAI LLMs with MATLAB

The [llms-with-matlab](https://github.com/matlab-deep-learning/llms-with-matlab) repository provides a comprehensive interface for connecting MATLAB to large language models like OpenAI's GPT-5. This enables you to leverage AI capabilities for code generation, data analysis, and scientific research tasks directly within your MATLAB workflow.

### Installation

{% hint style="info" %}
The MATLAB R2025b app version in Nuvolos (updated 2026-01-08) already has the llms-with-matlab add-on pre-installed on startup. You can start using it immediately without manual installation.
{% endhint %}

If you're using an older MATLAB version or need to install manually, clone the llms-with-matlab repository and add it to your MATLAB path:

```matlab
% Clone the repository (run in terminal or use MATLAB's system command)
% git clone https://github.com/matlab-deep-learning/llms-with-matlab.git /files/.matlab/llms-with-matlab

% Add the repository to your MATLAB path
addpath('/files/.matlab/llms-with-matlab')
```

Alternatively, you can download the repository as a ZIP file and extract it to your workspace.

### Configuration with OpenAI API

To use the llms-with-matlab tools with OpenAI's GPT-5 model, you need to configure your API key.

{% hint style="warning" %}
You need an OpenAI API key from a paid OpenAI API account. A ChatGPT subscription is not sufficient - you must create an API key at [platform.openai.com/api-keys](https://platform.openai.com/api-keys).
{% endhint %}

We recommend storing your OpenAI API key as a Nuvolos secret, which will be automatically exposed as an environment variable in your MATLAB application. See [Environment Variables and Secrets](https://docs.nuvolos.com/features/environment-variables-and-secrets) for details on how to set up secrets.

Set up your `OPENAI_API_KEY` as a Nuvolos secret. Once configured, the secret will be available as an environment variable when your MATLAB application starts.

You can verify the environment variable is available in MATLAB:

```matlab
% Check if the API key is set
getenv('OPENAI_API_KEY')
```

### Basic Chat Completion Example

Here's a simple example to get started with chat completions using GPT-5:

```matlab
% Create an openAIChat object with GPT-5
chat = openAIChat("You are a helpful MATLAB assistant.", ModelName="gpt-5");

% Generate a simple response
response = generate(chat, "How do I calculate the mean of a vector in MATLAB?")

% Continue the conversation with context
messages = messageHistory;
messages = addUserMessage(messages, "What is the best way to visualize data in MATLAB?");
[text, message] = generate(chat, messages);
disp(text);

% Generate code with specific constraints
codePrompt = "Write a MATLAB function that loads a CSV file and plots the first two columns.";
code = generate(chat, codePrompt, MaxNumTokens=500)
```

This will produce responses like:

```matlab
response = 
    "To calculate the mean of a vector in MATLAB, use the mean() function. 
     For example: x = [1, 2, 3, 4, 5]; avg = mean(x);"
```

### Example: Analyzing Scientific Papers and Generating Replication Code

This example demonstrates how to use the llms-with-matlab repository to analyze a scientific paper and generate MATLAB code for replicating the methodology. The example is based on the [AnalyzeScientificPapersUsingFunctionCalls](https://github.com/matlab-deep-learning/llms-with-matlab/blob/main/examples/AnalyzeScientificPapersUsingFunctionCalls.md) workflow.

#### Step 1: Set Up OpenAI Chat with Function Calling

Create an `openAIChat` object configured to interact with GPT-5 and define a custom function for extracting paper details:

```matlab
% Define a function to store paper analysis results
function storePaperAnalysis(paperTitle, methodology, matlabCode)
    filename = "paper_analysis.csv";
    T = table(paperTitle, methodology, matlabCode, ...
              VariableNames=["PaperTitle", "Methodology", "MATLABCode"]);
    writetable(T, filename, WriteMode="append");
end

% Create an openAIFunction to describe the analysis function
f = openAIFunction("storePaperAnalysis", ...
    "Function to store paper analysis including methodology and replication code.");
f = addParameter(f, "paperTitle", type="string", ...
    description="Title of the scientific paper.");
f = addParameter(f, "methodology", type="string", ...
    description="Summary of the paper's methodology.");
f = addParameter(f, "matlabCode", type="string", ...
    description="MATLAB code to replicate the paper's analysis.");

% Create chat objects with GPT-5
paperAnalyzer = openAIChat(...
    "You are an expert in analyzing scientific papers and generating MATLAB code. " + ...
    "Extract the methodology and generate clean, executable MATLAB code for replication.", ...
    Tools=f, ModelName="gpt-5");
```

#### Step 2: Analyze a Scientific Paper

Provide the paper content or URL to the model and request analysis:

```matlab
% Example: Analyze a paper on signal processing
paperContent = "Paper Title: Advanced Signal Processing Using Wavelet Transforms..." + newline + ...
    "Abstract: This paper presents a novel approach to signal denoising using " + ...
    "discrete wavelet transforms (DWT). We apply db4 wavelets with 5 decomposition " + ...
    "levels to noisy ECG signals..." + newline + ...
    "Methodology: 1) Load ECG signal, 2) Apply DWT with db4 wavelet, " + ...
    "3) Threshold detail coefficients, 4) Reconstruct signal using inverse DWT.";

% Request the model to analyze the paper
prompt = "Given the following paper:" + newline + paperContent + newline + ...
    "Extract the methodology and generate MATLAB code that replicates the analysis. " + ...
    "The code should be complete, executable, and include comments explaining each step.";

[text, response] = generate(paperAnalyzer, prompt);
```

#### Step 3: Handle Function Calls and Execute Code

Process the model's response and extract the generated MATLAB code:

```matlab
% Check if the model requested a function call
if isfield(response, "tool_calls")
    funCall = response.tool_calls;
    
    % Verify the function name
    if funCall.function.name == "storePaperAnalysis"
        % Parse the function arguments
        funArgs = jsondecode(funCall.function.arguments);
        
        % Display the generated MATLAB code
        disp("Generated MATLAB Code:");
        disp("=====================");
        disp(funArgs.matlabCode);
        
        % Optionally, save the analysis
        storePaperAnalysis(string(funArgs.paperTitle), ...
                          string(funArgs.methodology), ...
                          string(funArgs.matlabCode));
        
        % Execute the generated code (be cautious with this step)
        % eval(funArgs.matlabCode);
    end
end
```

#### Example Output

The model might generate MATLAB code like this:

```matlab
% Replication Code for: Advanced Signal Processing Using Wavelet Transforms
% This code replicates the wavelet-based signal denoising methodology

% Step 1: Load or generate a noisy ECG signal
fs = 1000; % Sampling frequency (Hz)
t = 0:1/fs:2; % Time vector (2 seconds)
cleanSignal = sin(2*pi*5*t) + sin(2*pi*15*t); % Simulated ECG
noisySignal = cleanSignal + 0.5*randn(size(t)); % Add noise

% Step 2: Apply Discrete Wavelet Transform (DWT)
waveletName = 'db4'; % Daubechies 4 wavelet
level = 5; % Decomposition level
[C, L] = wavedec(noisySignal, level, waveletName);

% Step 3: Threshold detail coefficients (soft thresholding)
sigma = median(abs(C))/0.6745; % Estimate noise level
threshold = sigma * sqrt(2*log(length(noisySignal)));
C_thresh = wthresh(C, 's', threshold); % Soft thresholding

% Step 4: Reconstruct the denoised signal
denoisedSignal = waverec(C_thresh, L, waveletName);

% Step 5: Visualize results
figure;
subplot(3,1,1); plot(t, cleanSignal); title('Clean Signal');
subplot(3,1,2); plot(t, noisySignal); title('Noisy Signal');
subplot(3,1,3); plot(t, denoisedSignal); title('Denoised Signal');
xlabel('Time (s)');
```

### Additional Use Cases

The llms-with-matlab repository supports many other applications:

* **Code optimization**: Ask the model to improve existing MATLAB code
* **Documentation generation**: Generate comments and help text for functions
* **Algorithm selection**: Get recommendations for appropriate algorithms based on your data
* **Debugging assistance**: Describe errors and get suggestions for fixes

For more examples and documentation, visit the [llms-with-matlab repository](https://github.com/matlab-deep-learning/llms-with-matlab).

## MATLAB Copilot

MATLAB Copilot is an AI assistant built for the MATLAB desktop environment. It helps with MATLAB workflows, code generation, code explanations, error troubleshooting, autocomplete, and test creation. It is included with campus-wide MATLAB licenses and does not require a GitHub account, OpenAI account, or API key.

{% hint style="info" %}
MATLAB Copilot is available as part of campus-wide MATLAB licenses and does not require a GitHub account, OpenAI account, or API key. It is a separate service from GitHub Copilot and the OpenAI API integration described above.
{% endhint %}

### Key Features

MATLAB Copilot offers several capabilities to enhance your MATLAB productivity:

* **Chat with MATLAB Copilot**: Ask questions and get responses based on MathWorks documentation and code examples
* **Generate or Modify Code**: Describe the code you want, and MATLAB Copilot will create new code or edit existing code
* **Code Explanations**: Get easy-to-follow explanations of unfamiliar code or add comments to your code
* **Error Explanations**: Receive explanations and troubleshooting recommendations for error messages
* **Autocomplete Code**: Save time with automatically generated code predictions as you type
* **Create Tests**: Generate test cases to verify code correctness (requires MATLAB Test)

### Getting Started

MATLAB Copilot is available in recent versions of MATLAB and requires a valid license. To start using MATLAB Copilot:

1. **Open Copilot Chat**: In the MATLAB desktop, access the Copilot Chat panel from the toolbar or use the keyboard shortcut
2. **Ask Questions**: Type your questions or requests in natural language
3. **Review Suggestions**: MATLAB Copilot will provide code snippets, explanations, or solutions based on your request
4. **Insert Code**: Accept suggestions to insert generated code directly into your scripts

### Example Usage

Here are some common ways to use MATLAB Copilot:

```matlab
% Example 1: Ask for help in Copilot Chat
% "How do I read a CSV file and plot the first two columns?"

% Example 2: Get code explanations
% Select code in the editor, right-click, and choose "Explain Code with Copilot"

% Example 3: Fix errors
% When an error occurs, click on the error message and select "Get help with Copilot"

% Example 4: Generate tests
% Right-click on a function and select "Generate Tests with Copilot"
```

### Best Practices

* **Be specific**: Provide clear and detailed descriptions of what you want to achieve
* **Iterate**: Refine your requests based on the initial responses
* **Verify**: Always review and test generated code before using it in production
* **Learn**: Use explanations to understand MATLAB concepts and improve your skills

For more information about MATLAB Copilot, including tutorials and detailed documentation, visit the [MATLAB Copilot product page](https://www.mathworks.com/products/matlab-copilot.html) or access the [Introduction to MATLAB Copilot course](https://www.coursera.org/learn/matlab-copilot).
