MATLAB Central Discussions - Join the conversation!
Sign in to participate

Updated Discussions

saket singh
saket singh
Last activity about 6 hours ago

hello i found the following tools helpful to write matlab programs. copilot.microsoft.com chatgpt.com/gpts gemini.google.com and ai.meta.com. thanks a lot and best wishes.
Aochen Xiao
Aochen Xiao
Last activity about 15 hours ago

It is April 3, 2025 now. Where is the MATLAB 2025a?

Los invito a conocer el libro "Sistemas dinámicos en contexto: Modelación matemática, simulación, estimación y control con MATLAB", el cual ya está disponible en formato digital.
El libro integra diversos temas de los sistemas dinámicos desde un punto de vista práctico utilizando programas de MATLAB y simulaciones en Simulink y utilizando métodos numéricos (ver enlace). Existe mucho material en el blog del libro con posibilidades para comentarios, propuestas y correcciones. Resalto los casos de estudio
Creo que el libro les puede dar un buen panorama del área con la posibilidad de experimentar de manera interactiva con todo el material de MATLAB disponible en formato Live Script. Lo mejor es que se pueden formular preguntas en el blog y hacer propuestas al autor de ejercicios resueltos.
Son bienvenidos los comentarios, sugerencias y correcciones al texto.
Steve Eddins
Steve Eddins
Last activity on 16 Apr 2025 at 14:10

In 2019, I wrote a MATLAB Central blog post called "The tool builder's gene (or how to get a job at MathWorks)." In it, I explained my personal theory of a characteristic of some engineers that is key for becoming successful software developers at MathWorks.
I just shared this essay on my personal blog, along with a couple of updates.
Steve Eddins
Steve Eddins
Last activity on 15 Apr 2025 at 21:13

Over the last 5 years or so, the highest-traffic post on my MATLAB Central image processing blog was not actually about image processing; it was about changing the default line thickness in plots.
Now I have written about some other MATLAB plotting behavior that I have recently changed to suit my own preferences. See this new blog post.
Here is a standard MATLAB plot:
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2)
I don't like some aspects of this plot, and so I have put the following code into my startup file.
set(groot,"DefaultLineLineWidth",2)
set(groot,"DefaultAxesXLimitMethod","padded")
set(groot,"DefaultAxesYLimitMethod","padded")
set(groot,"DefaultAxesZLimitMethod","padded")
set(groot,"DefaultAxesXGrid","on")
set(groot,"DefaultAxesYGrid","on")
set(groot,"DefaultAxesZGrid","on")
With those defaults changed, here is my preferred appearance:
plot(x,y1,x,y2)

Starting in MATLAB R2022a, use the append option in exportgraphics to create GIF files from animated axes, figures, or other visualizations.

This basic template contains just two steps:

% 1. Create the initial image file
gifFile = 'myAnimation.gif';
exportgraphics(obj, gifFile);
% 2. Within a loop, append the gif image
for i = 1:20
      %   %   %   %   %   %    % 
      % Update the figure/axes %
      %   %   %   %   %   %    % 
      exportgraphics(obj, gifFile, Append=true);
  end

Note, exportgraphics will not capture UI components such as buttons and knobs and requires constant axis limits.

To create animations of images or more elaborate graphics, learn how to use imwrite to create animated GIFs .

Share your MATLAB animated GIFs in the comments below!

See Also

This Community Highlight is attached as a live script

Can anyone provide some matlab learning paths, I am a novice to MATLAB, I would appreciate it
clc; clear; close all;
% Initial guess for [x1, x2, x3] (adjust as needed)
x0 = [0.2,0.35,0.5];
% No linear constraints
A = []; b = [];
Aeq = []; beq = [];
% Lower and upper bounds (adjust based on the problem)
lb = [0,0,0];
ub = [pi/2,pi/2,pi/2];
% Optimization options
options = optimoptions('fmincon', 'Algorithm', 'sqp', 'Display', 'iter');
% Solve with fmincon
[x_opt, fval, exitflag] = fmincon(@objective, x0, A, b, Aeq, beq, lb, ub, @nonlinear_constraints, options);
Iter Func-count Fval Feasibility Step Length Norm of First-order step optimality 0 4 4.125000e-01 1.537e+00 1.000e+00 0.000e+00 1.000e+00 1 8 5.464781e-01 9.718e-01 1.000e+00 2.734e-01 1.613e+01 2 12 4.828194e-01 6.526e-02 1.000e+00 9.158e-02 1.518e+01 3 41 4.828194e-01 6.526e-02 3.220e-05 9.264e-07 1.518e+01 Converged to an infeasible point. fmincon stopped because the size of the current step is less than the value of the step size tolerance but constraints are not satisfied to within the value of the constraint tolerance.
% Display results
fprintf('Optimal Solution: x1 = %.4f, x2 = %.4f, x3 = %.4f\n', x_opt(1), x_opt(2), x_opt(3));
Optimal Solution: x1 = 0.1879, x2 = 0.2227, x3 = 0.6308
fprintf('Exit Flag: %d\n', exitflag);
Exit Flag: -2
%% Objective function (minimizing sum of squared errors)
function f = objective(x)
f = sum(x.^2); % Dummy function (since we only want to solve equations)
end
%% Nonlinear constraints (representing the trigonometric equations)
function [c, ceq] = nonlinear_constraints(x)
% Example nonlinear trigonometric equations:
ceq(1) = cos(x(1))+cos(x(2))+cos(x(3))-3*0.9; % First equation
ceq(2) = cos(5*x(1))+cos(5*x(2))+cos(5*x(3)); % Second equation
ceq(3) = cos(7*x(1))+cos(7*x(2))+cos(7*x(3)); % Third equation
c = [x(1)-x(2); x(2)-x(3)]; % No inequality constraints
end
Adam Danz
Adam Danz
Last activity on 10 Apr 2025 at 22:29

I rarely/never save .fig files
47%
Continue working on it later
16%
Archive for future reference
23%
Share within my organization
10%
Share outside my organization
2%
Other (please leave a comment)
2%
2097 votes
I have written, tested, and prepared a function with four subsunctions on my computer for solving one of the problems in the list of Cody problems in MathWorks in three days. Today, when I wanted to upload or copy paste the codes of the function and its subfunctions to the specified place of the problem of Cody page, I do not see a place to upload it, and the ability to copy past the codes. The total of the entire codes and their documentations is about 600 lines, which means that I cannot and it is not worth it to retype all of them in the relevent Cody environment after spending a few days. I would appreciate your guidance on how to enter the prepared codes to the desired environment in Cody.
I'm getting this annoying survey (screenshot below) in the help windows of MATLAB R2024b this morning. It blocks the text I'm actually trying to read, when minimised it pops up again after a few minutes, and persists even after picking an option and completing the SurveyMonkey survey it links to. I don't even know what the OPC UA server so rest assured any of my answers to that survey aren't going to help MathWorks improve their product.
Gregory Vernon
Gregory Vernon
Last activity on 7 Apr 2025 at 5:31

I've long used the Tensor Toolbox from Sandia in order to use tensors in Matlab, but recently found myself wanting to apply it on symbolic arguments, which don't appear supported. Some google-fu'ing resulted in (non-free) Tensorlab and some file-exchange entries of mixed quality. And of course, there's the recent tensorprod, which a) doesn't support symbolics and b) arguments aren't strictly tensors (rather "representations of tensors in a matrix type").
This all got me to thinking that it would be mighty nice to have general / native / comprehensive support for a tensor class in official Matlab - even if it were in a separate toolbox.
No
50%
Yes, but I am not interested
8%
Yes, but it is too expensive
20%
Yes, I would like to know more
18%
Yes, I am cert. MATLAB Associate
2%
Yes, I am cert. MATLAB Professional
3%
4779 votes
Let's say MathWorks decides to create a MATLAB X release, which takes a big one-time breaking change that abandons back-compatibility and creates a more modern MATLAB language, ditching the unfortunate stuff that's around for historical reasons. What would you like to see in it?
I'm thinking stuff like syntax and semantics tweaks, changes to function behavior and interfaces in the standard library and Toolboxes, and so on.
(The "X" is for major version 10, like in "OS X". Matlab is still on version 9.x even though we use "R20xxa" release names now.)
What should you post where?
Wishlist threads (#1 #2 #3 #4 #5): bugs and feature requests for Matlab Answers
Frustation threads (#1 #2): frustrations about usage and capabilities of Matlab itself
Missing feature threads (#1 #2): features that you whish Matlab would have had
Next Gen threads (#1): features that would break compatibility with previous versions, but would be nice to have
@anyone posting a new thread when the last one gets too large (about 50 answers seems a reasonable limit per thread), please update this list in all last threads. (if you don't have editing privileges, just post a comment asking someone to do the edit)
Me: If you have parallel code and you apply this trick that only requires changing one line then it might go faster.
Reddit user: I did and it made my code 3x faster
Not bad for just one line of code!
Which makes me wonder. Could it make your MATLAB program go faster too? If you have some MATLAB code that makes use of parallel constructs like parfor or parfeval then start up your parallel pool like this
parpool("Threads")
before running your program.
The worst that will happen is you get an error message and you'll send us a bug report....or maybe it doesn't speed up much at all....
....or maybe you'll be like the Reddit user and get 3x speed-up for 10 seconds work. It must be worth a try...after all, you're using parallel computing to make your code faster right? May as well go all the way.
In an artificial benchmark I tried, I got 10x speedup! More details in my recent blog post: Parallel computing in MATLAB: Have you tried ThreadPools yet? » The MATLAB Blog - MATLAB & Simulink
Give it a try and let me know how you get on.
Hello, everyone! I’m Mark Hayworth, but you might know me better in the community as Image Analyst. I've been using MATLAB since 2006 (18 years). My background spans a rich career as a former senior scientist and inventor at The Procter & Gamble Company (HQ in Cincinnati). I hold both master’s & Ph.D. degrees in optical sciences from the College of Optical Sciences at the University of Arizona, specializing in imaging, image processing, and image analysis. I have 40+ years of military, academic, and industrial experience with image analysis programming and algorithm development. I have experience designing custom light booths and other imaging systems. I also work with color and monochrome imaging, video analysis, thermal, ultraviolet, hyperspectral, CT, MRI, radiography, profilometry, microscopy, NIR, and Raman spectroscopy, etc. on a huge variety of subjects.
I'm thrilled to participate in MATLAB Central's Ask Me Anything (AMA) session, a fantastic platform for knowledge sharing and community engagement. Following Adam Danz’s insightful AMA on staff contributors in the Answers forum, I’d like to discuss topics in the area of image analysis and processing. I invite you to ask me anything related to this field, whether you're seeking recommendations on tools, looking for tips and tricks, my background, or career development advice. Additionally, I'm more than willing to share insights from my experiences in the MATLAB Answers community, File Exchange, and my role as a member of the Community Advisory Board. If you have questions related to your specific images or your custom MATLAB code though, I'll invite you to ask those in the Answers forum. It's a more appropriate forum for those kinds of questions, plus you can get the benefit of other experts offering their solutions in addition to me.
For the coming weeks, I'll be here to engage with your questions and help shed light on any topics you're curious about.
看到知乎有用Origin软件绘制3D瀑布图,觉得挺美观的,突然也想用MATLAB复现一样的图,借助ChatGPT,很容易写出代码,相对Origin软件,无需手动干预调整图像属性,代码控制性强:
%% 清理环境
close all; clear; clc;
%% 模拟时间序列
t = linspace(0,12,200); % 时间从 0 到 12,分 200 个点
% 下面构造一些模拟的"峰状"数据,用于演示
% 你可以根据需要替换成自己的真实数据
rng(0); % 固定随机种子,方便复现
baseIntensity = -20; % 强度基线(z 轴的最低值)
numSamples = 5; % 样本数量
yOffsets = linspace(20,140,numSamples); % 不同样本在 y 轴上的偏移
colors = [ ...
0.8 0.2 0.2; % 红
0.2 0.8 0.2; % 绿
0.2 0.2 0.8; % 蓝
0.9 0.7 0.2; % 金黄
0.6 0.4 0.7]; % 紫
% 构造一些带多个峰的模拟数据
dataMatrix = zeros(numSamples, length(t));
for i = 1:numSamples
% 随机峰参数
peakPositions = randperm(length(t),3); % 三个峰位置
intensities = zeros(size(t));
for pk = 1:3
center = peakPositions(pk);
width = 10 + 10*rand; % 峰宽
height = 100 + 50*rand; % 峰高
% 高斯峰
intensities = intensities + height*exp(-((1:length(t))-center).^2/(2*width^2));
end
% 再加一些小随机扰动
intensities = intensities + 10*randn(size(t));
dataMatrix(i,:) = intensities;
end
%% 开始绘图
figure('Color','w','Position',[100 100 800 600],'Theme','light');
hold on; box on; grid on;
for i = 1:numSamples
% 构造 fill3 的多边形顶点
xPatch = [t, fliplr(t)];
yPatch = [yOffsets(i)*ones(size(t)), fliplr(yOffsets(i)*ones(size(t)))];
zPatch = [dataMatrix(i,:), baseIntensity*ones(size(t))];
% 使用 fill3 填充面积
hFill = fill3(xPatch, yPatch, zPatch, colors(i,:));
set(hFill,'FaceAlpha',0.8,'EdgeColor','none'); % 调整透明度、去除边框
% 在每条曲线尾部标注 Sample i
text(t(end)+0.3, yOffsets(i), dataMatrix(i,end), ...
['Sample ' num2str(i)], 'FontSize',10, ...
'HorizontalAlignment','left','VerticalAlignment','middle');
end
%% 坐标轴与视角设置
xlim([0 12]);
ylim([0 160]);
zlim([-20 350]);
xlabel('Time (sec)','FontWeight','bold');
ylabel('Frequency (Hz)','FontWeight','bold');
zlabel('Intensity','FontWeight','bold');
% 设置刻度(根据需要微调)
set(gca,'XTick',0:2:12, ...
'YTick',0:40:160, ...
'ZTick',-20:40:200);
% 设置视角(az = 水平旋转,el = 垂直旋转)
view([211 21]);
% 让三维坐标轴在后方
set(gca,'Projection','perspective');
% 如果想去掉默认的坐标轴线,也可以尝试
% set(gca,'BoxStyle','full','LineWidth',1.2);
%% 可选:在后方添加一个浅色网格平面 (示例)
% 这个与题图右上方的网格类似
[Xplane,Yplane] = meshgrid([0 12],[0 160]);
Zplane = baseIntensity*ones(size(Xplane)); % 在 Z = -20 处画一个竖直面的框
surf(Xplane, Yplane, Zplane, ...
'FaceColor',[0.95 0.95 0.9], ...
'EdgeColor','k','FaceAlpha',0.3);
%% 进一步美化(可根据需求调整)
title('3D Stacked Plot Example','FontSize',12);
constantplane("x",12,FaceColor=rand(1,3),FaceAlpha=0.5);
constantplane("y",0,FaceColor=rand(1,3),FaceAlpha=0.5);
constantplane("z",-19,FaceColor=rand(1,3),FaceAlpha=0.5);
hold off;
Have fun! Enjoy yourself!
Hello Community,
We're excited to announce that registration is now open for the MathWorks AUTOMOTIVE CONFERENCE 2025! This event presents a fantastic opportunity to connect with MathWorks and industry experts while exploring the latest trends in the automotive sector.
Event Details:
  • Date: April 29, 2025
  • Location: St. John’s Resort, Plymouth, MI
Featured Topics:
  • Virtual Development
  • Electrification
  • Software Development
  • AI in Engineering
Whether you're a professional in the automotive industry or simply interested in these cutting-edge topics, we highly encourage you to register for this conference.
We look forward to seeing you there!

About Discussions

Discussions is a user-focused forum for the conversations that happen outside of any particular product or project.

Get to know your peers while sharing all the tricks you've learned, ideas you've had, or even your latest vacation photos. Discussions is where MATLAB users connect!

More Community Areas

MATLAB Answers

Ask & Answer questions about MATLAB & Simulink!

File Exchange

Download or contribute user-submitted code!

Cody

Solve problem groups, learn MATLAB & earn badges!

Blogs

Get the inside view on MATLAB and Simulink!

AI Chat Playground

Use AI to generate initial draft MATLAB code, and answer questions!