다음에 대한 결과:
The example code below shows how to write version 7.3 MAT files directly from C++ using the HDF5 library (libhdf5) and HighFive, a header-only C++ wrapper for libhdf5. Version 7.3 MAT files are HDF5-based, but contain a proprietary header in the first 512 bytes of the file.
The implementation performs three primary tasks:
First, it creates an HDF5 file with a 512-byte userblock. After data has been added into the file, the file is closed. Then a 128-byte header is written into the userblock so that the file is recognized by MATLAB as a valid version-7.3 MAT file. This is done in function “makeMatHeader”.
Second, MATLAB-specific metadata attributes are added to each dataset. Attributes such as “MATLAB_class” and “MATLAB_int_decode” inform MATLAB how each dataset should be interpreted.
Third, MATLAB-compatible complex datasets are created by overriding HighFive's default complex-number layout. HighFive uses the field names `r` and `i` by default, while MATLAB expects `real` and `imag`. A Highfive custom compound type is therefore registered for `std::complex<double>` using the MATLAB field names.
With these changes in place, C++ code can write scalar values, vectors, structs, complex arrays, and character arrays to a file that MATLAB can read as a version 7.3 MAT file.
#include <iostream>
#include <vector>
#include <complex>
#include <cstddef>
#include <fstream>
#include <string>
#include <cstdint>
#include <utility>
#include <bitset>
#include <highfive/highfive.hpp>
#include "hdf5.h"
// Modify the 512-byte userblock at the front of the HDF5 file to make it compatible with MATLAB's v7.3 MAT file format.
void makeMatHeader(std::string filename)
{
char header[512]; // MATLAB-style header for HDF5 file
memset(header, 0, sizeof(header)); // Initialize header to all zeros
// Example header content
snprintf(header, sizeof(header), "MATLAB 7.3 MAT-file, Platform: HDF5");
header[124] = 0;
header[125] = 2;
// I/M indicate little-endian format (Intel Mac/Windows)
header[126] = 'I';
header[127] = 'M';
// Write the header to the beginning of the file
std::ofstream outFile(filename, std::ios::binary | std::ios::in | std::ios::out);
outFile.seekp(0);
outFile.write(header, sizeof(header));
outFile.close();
}
// https://www.geeksforgeeks.org/dsa/inplace-m-x-n-size-matrix-transpose/
void MatrixInplaceTranspose(int *A, int rows, int cols)
{
// Moves elements in-place to achieve the transpose.
// A is a pointer to a 2D array, rows is the number of rows, and cols is the number of columns.
int size = rows*cols - 1;
int t; // holds element to be replaced, eventually becomes next element to move
int next; // location of 't' to be moved
int cycleBegin; // holds start of cycle
int i; // iterator
const int HASH_SIZE = 8192; // define a suitable hash size for the bitset. Must be at least as large as the number of elements in the matrix.
std::bitset<HASH_SIZE> b; // hash to mark moved elements. Must be large enough to cover all indices.
if (rows <= 0 || cols <= 0) {
throw std::invalid_argument("Matrix dimensions must be positive");
}
else if ((rows * cols) > HASH_SIZE)
{
throw std::invalid_argument("Matrix size exceeds hash size for in-place transpose. Increase the HASH_SIZE constant.");
}
b.reset();
b[0] = b[size] = 1;
i = 1; // Note that A[0] and A[size-1] won't move
while (i < size)
{
cycleBegin = i;
t = A[i];
do
{
// Input matrix [rows x cols]
// Output matrix [cols x rows]
// i_new = (i*rows)%(N-1)
next = (i*rows)%size;
std::swap(A[next], t);
b[i] = 1;
i = next;
}
while (i != cycleBegin);
// Get Next Move (what about querying random location?)
for (i = 1; (i < size) && b[i]; i++)
;
}
}
template <typename T>
std::vector<std::vector<T>> transpose(const std::vector<std::vector<T>>& matrix)
{
// Performs a nonconjugate transpose on a vector of vectors
// The input matrix is a vector of vectors, where each inner vector represents a row of the matrix.
// Handle empty matrix edge case
if (matrix.empty() || matrix[0].empty()) {
return {};
}
size_t rows = matrix.size();
size_t cols = matrix[0].size();
// Initialize the transposed matrix with flipped dimensions: cols x rows
std::vector<std::vector<T>> transposed(cols, std::vector<T>(rows));
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < cols; ++j) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}
// Creates a HighFive compound type for representing MATLAB-style complex numbers
// HighFive by default uses r/i but that is not compatible with MATLAB's complex number representation, which uses real/imag.
HighFive::CompoundType matlabComplexDouble () {
return {
{"real", HighFive::AtomicType<double>{}},
{"imag", HighFive::AtomicType<double>{}}
};
}
// Register the CompoundType to represent std::complex<double>
HIGHFIVE_REGISTER_TYPE(std::complex<double>, matlabComplexDouble);
int main()
{
const std::string filename = "test.mat";
// Needed for the complex number literal suffix 'i'
using namespace std::literals;
/*
* MATLAB vs C++ array layout
*
* MATLAB stores arrays in column-major order, meaning values in the same column are
* laid out next to each other in memory. Typical C++ containers such as nested std::vector and arrays
* are written in row-major order, where values in the same row are adjacent in memory.
*
* That difference matters when something such as a 2D dataset is exchanged from C++ to MATLAB. A 2x3
* matrix written from C++ in row-major order will be interpreted by MATLAB as a 3x2 matrix, transposed relative
* to the original C++ layout. The user will have to transpose the array to view the original C++ layout
* correctly.
*
* C++ developers need to be aware of the memory layout when
* exchanging multidimensional arrays with MATLAB. To maintain the structure,
* one will need to transpose the array before writing it to the mat file.
*/
// Test data
// 2x3 Array of complex double
std::vector<std::vector<std::complex<double>>> dataComplex = {{10.0 + 1.0i, 20.0 + 2.0i, 30.0 + 3.0i},
{40.0 + 4.0i, 50.0 + 5.0i, 60.0 + 6.0i}};
// 1x3 Vector of double
std::vector<double> dataDoubleVec = {1.1, 2.2, 3.3};
// 1x5 Array of integers
int dataIntArray[5] = {1, 2, 3, 4, 5};
// 2x4 Array of integers
int dataIntArray2x4[2][4] = {{1, 2, 3, 4},
{5, 6, 7, 8}};
int dataInt = 79;
double dataDouble = 3.14;
std::string dataString = "Hello, MATLAB!!!!!";
{
// Put the highfive related code into its own block so that the file gets closed when the file object is no longer in scope.
// Create a highfive file create property, get the underlying HDF5 property ID, and set a userblock size
HighFive::FileCreateProps fcp = HighFive::FileCreateProps::Empty();
hid_t fcpl_id = fcp.getId();
H5Pset_userblock(fcpl_id, 512);
HighFive::File file(filename, HighFive::File::Truncate, fcp);
// Storing a double to the file
// For something that is only a single value, must create a 1x1 dataspace
HighFive::DataSpace scalarDoubleSpace({1, 1});
// This creates a variable in the MATLAB workspace with the name "double_value"
HighFive::DataSet doubleField = file.createDataSet<double>("double_value", scalarDoubleSpace);
doubleField.write(dataDouble);
// Metadata for MATLAB compatibility
doubleField.createAttribute("MATLAB_class", std::string("double"));
// Storing an integer to the file
// For something that is only a single value, must create a 1x1 dataspace
HighFive::DataSpace scalarIntSpace({1, 1});
// This creates a variable in the MATLAB workspace with the name "int_value"
HighFive::DataSet intField = file.createDataSet<int>("int_value", scalarIntSpace);
intField.write(dataInt);
// Metadata for MATLAB compatibility
intField.createAttribute("MATLAB_class", std::string("int32"));
// Storing a C-style 1x5 array of integers to the file
// Since it is a single dimension, there is no need to move the data, just reinterpret it as a 5x1 row-major array.
// When Matlab imports it, it will perceive it as a 1x5 column-major array.
// This line casts the 1x5 array to a 5x1 array to match MATLAB's column-major order
int (*numArrayTrans5x1)[1] = reinterpret_cast<int (*)[1]>(dataIntArray);
HighFive::DataSpace intArray5x1Space({5, 1});
// This creates a variable in the MATLAB workspace with the name "int_array"
HighFive::DataSet intArrayField = file.createDataSet<int>("int_array", intArray5x1Space);
intArrayField.write(numArrayTrans5x1);
intArrayField.createAttribute("MATLAB_class", std::string("int32"));
// Storing a C-style 2x4 array of integers to the file
// For something that is a multi-dimensional array, we need to transpose the array and create a dataspace with the dimensions swapped
// so that the data is stored in column-major order.
MatrixInplaceTranspose((int*)dataIntArray2x4, 2, 4);
// After moving the values around, we need to cast the array with the new dimensions to match the new layout
// Cast the transposed 2x4 array to a 4x2 array to match MATLAB's column-major order
int (*numArrayTrans)[2] = reinterpret_cast<int (*)[2]>(dataIntArray2x4);
HighFive::DataSpace intArray2x4Space({4, 2});
// This creates a variable in the MATLAB workspace with the name "int_array_2x4"
HighFive::DataSet intArray2x4Field = file.createDataSet<int>("int_array_2x4", intArray2x4Space);
intArray2x4Field.write(numArrayTrans);
intArray2x4Field.createAttribute("MATLAB_class", std::string("int32"));
// Creating a Matlab struct (HDF5 group)
HighFive::Group my_struct = file.createGroup("my_struct");
my_struct.createAttribute("MATLAB_class", std::string("struct"));
// The only difference between storing data into a struct or as a normal variable in the MAT file is the
// the parent object you use when you do "createDataSet".
// file.createDataSet would create a normal variable, my_struct.createDataSet creates it within the "my_struct" struct.
// Storing a string to the struct so that it will be accessible as a character array in MATLAB
// For something that is a string, we create a dataspace with dimensions [string_length, 1] and save the character data accordingly
// We create a vector that has dataString.size() elements, each of which is a char vector of size 1 to store individual characters.
std::vector<std::vector<char>> text_bytes(dataString.size(), std::vector<char>(1));
// MATLAB expects character arrays to be a row vector so we reshape it accordingly since dimensions are swapped between C++ and MATLAB
for (int i = 0; i < dataString.size(); ++i) {
text_bytes[i][0] = dataString[i];
}
HighFive::DataSpace charSpace({dataString.size(), 1});
// uint16_t is required for MATLAB character arrays
HighFive::DataSet textField = my_struct.createDataSet<uint16_t>("text_value", charSpace);
textField.write(text_bytes);
// Metadata for MATLAB compatibility
textField.createAttribute("MATLAB_class", std::string("char"));
// Tell MATLAB to interpret the data as characters rather than integers
textField.createAttribute("MATLAB_int_decode", 2);
// Storing a vector to the struct
// In order to transpose the vector correctly, we first wrap it in another vector to make it a 2D array.
std::vector<std::vector<double>> transposableDoubleVec = { dataDoubleVec };
// For vectors, we let HighFive infer the dataspace from the data itself
// Transpose the vector to match MATLAB's column-major order
HighFive::DataSet doubleVectorField = my_struct.createDataSet("double_vector", transpose(transposableDoubleVec));
// Metadata for MATLAB compatibility
doubleVectorField.createAttribute("MATLAB_class", std::string("double"));
// Storing a complex (and multi-dimensional) vector to the struct
// For multi-dimensional vectors, we need to perform a noncojugate transpose on the array to match
// MATLAB's column-major order so the data layout is consistent between C++ and MATLAB.
// For vectors, we let HighFive infer the dataspace from the data itself
HighFive::DataSet complexField = my_struct.createDataSet("complex_vector", transpose(dataComplex));
// Metadata for MATLAB compatibility
complexField.createAttribute("MATLAB_class", std::string("complex"));
}
// Finalize the MATLAB-compatible HDF5 file by writing the MATLAB header into the userblock
makeMatHeader(filename);
return 0;
}








All these examples are plotted using SHeatmap. For details, please refer to the relevant examples in the demo_SColorbar folder included in the toolbox.
For those using Matlab and ecountering difficulty with mex and Xcode v27
Fix for Xcode 27 breaking MATLAB MEX C++ compilation:
matlab
edit(fullfile(prefdir,'mex_C++_maca64.xml'))
% Set LINKEXPORTCPP=""
% Then rebuild normally
Hi everyone
Some of my colleauges at MathWorks are conducting a survey on how people use science and engineering file formats such as NetCDF, HDF5, Zarr and so on.
It will only take a few minutes to fill out and is completely anonymous unless you want to be contacted. Your thoughts, details of usage in your domain or industry, and current friction points will help us improve MATLAB to better support the kind of work you do in the future!
If there's anything not covered by the survey that you'd like to mention, feel free to reply to this thread.
Cheers,
Mike
TokaLab is an open-access virtual tokamak platform built in MATLAB for nuclear fusion modeling, diagnostics, inverse problems, and computational experimentation.
- App installer for MATLAB Online — run TokaLab directly in your browser.
- Two new tutorials covering the core modules, SimPla and SynDiag, in detail.
- Two new modules: TokaPlot for advanced plotting, and SynRad for radiation generation.
- Real tokamak geometries, supporting more realistic tokamak modeling.
You can use MATLAB's rat() function to obtain a rational approximation of a decimal value. For example, rat(0.625) gives a representation equivalent to 5/8. If you simply want to verify decimal/fraction conversions without running MATLAB, a browser-based decimal-to-fraction calculator can also be useful.
If you're a student looking for tips, resources, or guidance for learning MATLAB, check out my new blog: Learn MATLAB – A Student’s Guide
The blog highlights a variety of student resources, including getting started guides, cheat sheets, learning materials, and other helpful tools to make learning MATLAB easier. I hope you find it useful!

We heard your feedback that it can be difficult to find the latest comment or reply in long threads. To make this easier, you can now jump directly to the latest activity by clicking the latest activity date link at the top of the leaf page. See the screenshot below for an example. This is similar to the experience of MATLAB Answers today.
Thanks again for sharing your feedback and helping us improve the experience.

Very Favorable
21%
Favorable
22%
Neutral
20%
Unfavorable
17%
Very Unfavorable
20%
추천 수: 886
💡About
First, I would like to thank everyone who has downloaded my eds-classification repository so far. This post is meant for those who are currently using the repository or may be interested in using the repository in their research.
To keep things short, I have released v2.0 of the eds-classification series on GitHub and the File Exchange. The update comes with significant changes to the repository structure and functions, and so it is worth noting that the update will likely be incompatible with any scripts written using prior releases.
The update provides several key new features that are meant to improve usability and producton. If you are interested in seeing how eds-classification may help you with your mineralogy research, please check out the release notes for v2 and consider giving the repository a try.
Respectfully,
Austin
📝Release Notes
The full release notes for v2 are available here: https://github.com/weber1158/eds-classification/releases/tag/v2.0
⬇️Download Now



Annular, sector, triangular, and cluster heatmaps can all be produced by this tool:https://www.mathworks.com/matlabcentral/fileexchange/125520-special-heatmap
Demo: Group Sep with non-square matrix
Data = rand(3, 12);
SHM = SHeatmap(Data, 'Format','sq');
SHM.RowName = {'Off-peak', 'Peak', 'Regular'};
SHM.ColName = {'Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen'};
SHM.ColGroup = [1,1,1,1, 2,2,2,2, 3,3,3,3];
SHM.draw().setFrame()

Demo: Merge two triangle heatmaps
% Made up some data casually (随便捏造了点数据)
X = randn(20,15) + [(linspace(-1,2.5,20)').*ones(1, 6), (linspace(.5,-.7,20)').*ones(1, 5), (linspace(.9,-.2,20)').*ones(1, 4)];
% Get the correlation matrix (求相关系数矩阵)
Data = corr(X);
figure()
SHM_m1 = SHeatmap(Data, 'Format','sq').draw().setType('tril');
SHM_m1.setColLabel('Visible','off').setText()
SHM_m2 = SHeatmap(Data, 'Format','hex').draw().setType('triu0');
SHM_m2.setRowLabel('Visible','off').setColLabel('Visible','on') % Show the hidden Var-1 label (显示隐藏的 Var-1 标签)

Demo: Circular heatmap with Group Block and GroupSep
% Circular heatmap is currently supported only for
% SHeatmap with 'sq' Format and 'full' Type.
rng(1)
Data = randn(100, 5);
rowName = compose('row-%d', 1:100);
colName = compose('col-%d', 1:5);
rowGroup = [ones(1, 25), 2.*ones(1, 15), 3.*ones(1, 20), 4.*ones(1, 20), 5.*ones(1, 20)];
rowColor = [187,207,232; 222,236,247; 253,253,253; 251,225,216; 231,184,192]./255;
rgnames = {'Group-R1','Group-R2','Group-R3','Group-R4','Group-R5'};
% create figure (图窗创建)
fig = figure('Units','normalized', 'Position',[.1,.05,.5,.72]);
ax = axes('Parent',fig, 'Position',[.1,.1,.75,.75]);
% Draw group block (绘制分组方块)
SCB_L = SClusterBlock(ax, rowGroup, 'Orientation','left', 'ColorList',rowColor, 'Group',rowGroup, 'GroupSep',2.5);
SCB_L.draw(); SCB_L.setXYTLim('XLim',[1.65,1.95], 'YLim',[0, 1], 'TLim',[-3*pi/2, pi/3]);
% Draw circular heatmap (绘制环形热图)
SHM = SHeatmap(ax, Data, 'Format','sq', 'RowGroup',rowGroup, 'GroupSep',2.5);
SHM.TickLength = .3;
SHM.draw();
SHM.setRowName(rowName)
SHM.setColName(colName)
SHM.setRowLabelLocation('right')
SHM.setColLabelLocation('top')
% YLim(1) -> TLim(1), YLim(2) -> TLim(2)
SHM.setXYTLim('XLim',[2, 3], 'YLim',[0, 1], 'TLim',[-3*pi/2, pi/3]);
SHM.Colorbar.Position(1) = SHM.Colorbar.Position(1) + .1;
gHdl = text(ax, SCB_L.X, SCB_L.Y, rgnames, 'FontSize',14, 'FontName','Times New Roman');
setTextPerpRadial(gHdl)
colormap(slanCM(97, 32))

More than 50 examples are incorporated into this tool:

I often see the need of argument validation for which the arguments depend on each other.
function result = myFcn(points, attributes, queryIdx)
% INPUT
% points: [Nx3]
% attributes: [Nx1]
% queryIdx: [Mx1]
%
% OUTPUT
% result: [Mx1]
end
points and attributes depend in size, queryIdx and result as well. The current arguments/end block does not allow to formulate such constraints. The best you can do currently is
function result = myFcn(points, attributes, queryIdx)
arguments(Input)
points (:,3)
attributes (:,1)
queryIdx (:,1)
end
arguments(Output)
result (:,1)
end
assert(height(points) == height(attributes), "Argument validation failed")
...
assert(height(queryIdx) == height(result), "Argument validation failed")
end
Reading just the header without additional comments is unclear for a developer and prone to misunderstanding.
What do you think of the following language extension proposal?
function result = myFcn(points, attributes, queryIdx)
arguments(Input)
points (N,3)
attributes (N,1)
queryIdx (M,1)
end
arguments(Output)
result (M,1)
end
end
The intention is clear for the reader at first sight and gives you guarantees about input/output parameters (in contrast to simple comments). Validating the parameter "points" sets the (temporary) variable N, which can be reused in further argument validations. To be discussed if N and M are valid just within the arguments block or also in the whole function.
What is your opinion on such a language improvement?
What did you guys do? It's impossible to edit figures on the fly now. Even simple things like removing data series and then removing them from the legend have become impossible without meddling with code. It used to be you could do little touch ups and even copy series from one figure to the next in the most expeditious and simple way, that to me was a big plus of using Matlab over python. Now this is so backwards and unintuitive, what were you guys thinking?
AI writes all my code now
18%
Multiple times a day
24%
A few times a week
15%
A few times a month
7%
Only for suggestions
22%
It is not allowed for my work
14%
추천 수: 758
I've left Matlab Answers in spring 2023. At this time the forum was full of interesting programming questions, e.g about optimizing code. A bunch of experienced Matlab users have discussed diefferent approachs and compared them. Some questions have concerned beginner problems and home work solutions, others belonged to professionally used tools for scientific work
Every week some new tools for dailiy use have been posted in the FileExchange.
Today, 3 years later, the traffic is much lower and questions concern the correct usage of Matlab commands usually. Submissions in the FileExchange are very specific and rarely useful for general programming jobs.
What has happend?
Hi everyone,
Simulations have a way of outgrowing the machine they run on (at least mine do). Bigger sweeps, longer regression suites, more data to pull in. At some point your workstation just isn't beefy enough!
I've just published a post on running larger MATLAB and Simulink simulations in the cloud (e.g. AWS): more compute when we need it, without changing how we work day to day.
The example is from automotive, but the same applies to aerospace, robotics, and beyond.
If you want to read more, here's the link: https://blogs.mathworks.com/engineering/2026/07/14/on-scaling-model-based-design-into-the-cloud/
How are others handling scaling for simulation? what's working for you?
Cheers,
George

All figures presented in this Discussion were generated using MATLAB.


I developed two functions: one for plotting chord diagrams without self-loops, and the other for plotting chord diagrams with self-loops.
chordChart : basic usage
plotting chord diagrams without self-loops : https://www.mathworks.com/matlabcentral/fileexchange/116550-chordchart-chord-diagram
dataMat = [2 0 1 2 5 1 2;
3 5 1 4 2 0 1;
4 0 5 5 2 4 3];
colName = {'B1','G2','G3','G4','G5','G6','G7'};
rowName = {'S1','S2','S3'};
% Create and render chord diagram object (创建弦图对象并渲染)
CC = chordChart(dataMat, 'RowName',rowName, 'ColName',colName, 'Arrow','on');
CC.LinearMinorTick = 'on';
CC.draw();
% Set Font for labels and show ticks (调整字体并显示刻度)
CC.setFont('FontSize',17, 'FontName','Cambria')
CC.tickState('on')
CC.tickLabelState('on')

biChordChart : basic usage
plotting chord diagrams with self-loops : https://www.mathworks.com/matlabcentral/fileexchange/121043-bichordchart-bidirectional-chord-diagram
dataMat = randi([0,8], [5,5]);
nameList = {'AAA','BBB','CCC','DDD','EEE'};
% Create bichord chart object and draw (创建并绘制双向弦图对象)
BCC = biChordChart(dataMat, 'Arrow','on', 'Label',nameList);
BCC = BCC.draw();
% Show ticks and tick labels (添加刻度)
BCC.tickState('on')
BCC.tickLabelState('on')
% Set font properties (修改字体,字号及颜色)
BCC.setFont('FontName','Cambria','FontSize',17)

The two File Exchange submissions each provide more than a dozen basic examples. In addition, the GitHub repository listed below provides nearly 40 elaborate customized demonstration cases.













Looking for an on-campus job next semester? We’re hiring MATLAB Student Ambassadors to host fun events, share MATLAB resources on social media, and connect with your student community.
Learn more here: https://www.mathworks.com/academia/students/student-ambassadors.html

How does everyone use MatLab right now? I can't think of any ideas what i can use this software for!
Hi everyone
It is my pleasure to be able to report on a project that several teams at MathWorks have been working on for some time now. A new object management system that promises to make object oriented code in MATLAB a lot faster.
The new system is available as a limited beta in the pre-release of MATLAB 2026b. It is not turned on by default. If you are developing OOP code, we'd love you to try it out. Most of the time, no code changes will be necessary but there are a small number of well-defined case where you will need to update your code.
The team are currently looking for MATLAB developers to work with who would like to try this out.
More details, including how to join the beta, are available in the following blog post https://blogs.mathworks.com/matlab/2026/07/14/objects-are-about-to-get-much-faster-in-matlab/
Best wishes,
Mike