主要内容

搜索

clc; clear; close all;
% === COMMON DOMAIN SETUP ===
L = 1.0;
Nx = 41; Ny = 41;
dx = L / (Nx - 1);
dy = dx;
x = linspace(0, L, Nx);
y = linspace(0, L, Ny);
[X, Y] = meshgrid(x, y);
alpha = 1.0;
tol = 1e-5;
% === TRACK ITERATIONS ===
iterations_to_plot = [1 2 3 5 10 20 40 80 120 160 200];
%% === 1. STEADY-STATE SOLVER (Gauss-Seidel) ===
T_steady = zeros(Ny, Nx);
% Apply boundary conditions
T_steady(:,1) = 0; % Left
T_steady(:,end) = 0; % Right
T_steady(1,:) = 0; % Bottom
T_steady(end,:) = 1; % Top
residual = Inf;
iter = 0;
max_iter = 10000;
grad_vec_steady = []; % Khởi tạo mảng rỗng để lưu max gradient
T_steady_snapshots = cell(length(iterations_to_plot), 1);
snap_idx = 1;
while residual > tol && iter < max_iter
T_old = T_steady;
% Gauss-Seidel update
for j = 2:Ny-1
for i = 2:Nx-1
T_steady(j,i) = 0.25 * ( ...
T_steady(j+1,i) + T_steady(j-1,i) + ...
T_steady(j,i+1) + T_steady(j,i-1));
end
end
residual = max(max(abs(T_steady - T_old)));
iter = iter + 1;
% % --- Compute gradient magnitude ---
[Tx, Ty] = gradient(T_steady, dx, dy);
grad_mag = sqrt(Tx.^2 + Ty.^2);
grad_vec_steady(iter) = max(grad_mag(:));
% --- Save snapshot if needed ---
if snap_idx <= length(iterations_to_plot) && iter == iterations_to_plot(snap_idx)
T_steady_snapshots{snap_idx} = T_steady;
snap_idx = snap_idx + 1;
end
end
fprintf(' Steady-state converged in %d iterations. Final residual: %.2e\n', iter, residual);
Steady-state converged in 905 iterations. Final residual: 9.97e-06
% --- Plot Max Temperature Gradient vs Iteration ---
figure;
plot(1:iter, grad_vec_steady(1:iter), 'LineWidth', 1.5);
xlabel('Iteration');
ylabel('Max Temperature Gradient');
title('Maximum Temperature Gradient vs Iteration (Steady-State)');
grid on;
% --- Plot: Converged Steady-State Temperature Distribution ---
figure;
contourf(X, Y, T_steady, 20, 'LineColor', 'none');
colorbar;
xlabel('x');
ylabel('y');
title('Converged Steady-State Temperature Distribution (Gauss-Seidel)');
What is MATLAB Project?
40%
Never use it
28%
Only use existing from others' proj
3%
Use it occasionally
13%
Use it frequently
16%
90 个投票
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
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
上次活动时间: 2025-4-10

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.
Aochen Xiao
Aochen Xiao
上次活动时间: 2025-5-28,9:21

It is April 3, 2025 now. Where is the MATLAB 2025a?
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 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!
We are excited to announce another update to our Discussions area: the new Contribution Widget! The new widget simplifies the process of creating diverse types of content, whether you're praising someone who has helped you, sharing tips and tricks, or polling the community.
Previously, creating various types of content required navigating multiple links or channels. With the new Contribution Widget, everything you need is conveniently located in one place.
Give it a try and let us know how we can further enhance your user experience.
P.S. Who has been particularly helpful to you lately? Create your first praise post and let them know!
I am trying to integrate an external C++ function (large package) into a mex function. I have written a cmake file, which generates library for external C++ function and I am using matlab_add_mex to generate the mex-file.
# Find MATLAB
set(Matlab_ROOT_DIR "../mathworks/2023b/bin/")
find_package(Matlab REQUIRED)
# Add a MEX target
matlab_add_mex(
NAME my_mex_function
SRC my_mex_function.cpp
LINK_TO my_library
)
find_package(Matlab REQUIRED) - gives following error:
CMake Error at CMakeLists.txt: (find_package):
By not providing "Findmatlab.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "matlab", but CMake did not find one.
Could not find a package configuration file provided by "matlab" with any of the following names:
matlabConfig.cmake
matlab-config.cmake
Add the installation prefix of "matlab" to CMAKE_PREFIX_PATH or set "matlab_DIR" to a directory containing one of the above files. If "matlab" provides a separate development package or SDK, be sure it has been installed.
I searched for matlabConfig.cmake or matlab-config.cmake in matlab installation directory but did not find it. Does Matlab provide provide such files or not? If not how to integrate large C++ programs with MATLAB. I dont want to use system function calls as they are too slow.
There has been a lot of discussion here about the R2025a Prerelease that has really helped us get it ready for the prime time. Thank you for that!
A new update of the Prerelease has just dropped. So fresh it is still warm from the oven! In my latest blog post I discuss changes in the way MathWorks has been asking-for and processing feedback...and you have all been a part of that.
If you haven't tried the Prerelease in a while, I suggest you update and see how things are looking now.
If you have already submitted a bug report and it hasn't been fixed in this update, you don't need to submit another one. Everything is being tracked!
Have a play, discuss it here and thanks for again for being part of the process.
Bonsoir,
Je suis en train de finaliser Module 4 du cours "Designing and Simulating Physical Models" et j’ai quelques difficultés avec les derniers quiz, notamment ceux liés au projet Simulating Motor Heat Effects.
J’ai suivi toutes les étapes du projet et compris l’utilisation des blocs Relay, PS Product et Thermal Mass, mais j’aimerais avoir des clarifications sur :
Comment tester efficacement mon modèle pour vérifier que la logique de coupure fonctionne bien ?
Quels paramètres thermiques sont les plus critiques pour éviter les erreurs de simulation ?
Y a-t-il des erreurs fréquentes à éviter dans les quiz finaux ?
Si quelqu’un a réussi ces quiz et peut me donner quelques conseils ou orientations, ce serait super !
Merci beaucoup pour votre aide.

Bonsoir

Je me permets de vous contacter afin d’obtenir des informations et un encadrement concernant un projet sur lequel je travaille actuellement. Il s’agit d’une application visant à réguler un oscillateur quantique en potentiel harmonique à l’aide de l’intelligence artificielle.

Plus précisément, mon objectif est de :

Modéliser l’évolution de l’oscillateur quantique sous un potentiel harmonique.

Appliquer des techniques d’IA (réseaux de neurones, renforcement, etc.) pour optimiser la régulation de son état.

Analyser les performances des algorithmes dans le cadre de cette régulation.

Je souhaiterais savoir si vous pourriez m’apporter des conseils ou un encadrement dans la réalisation de ce projet, notamment sur les aspects mathématiques, physiques et computationnels impliqués. De plus, toute suggestion sur des références bibliographiques ou des outils adaptés (MATLAB, Python, TensorFlow, etc.) serait également très précieuse.

Dans l’attente de votre retour, Bien cordialement,

📢 We want to hear from you! We're a team of graduate student researchers at the University of Michigan studying MATLAB Drive and other cloud-based systems for sharing coding files. Your feedback will help improve these tools. Take our quick survey here: https://forms.gle/DnHs4XNAwBZvmrAw6
Hello,
I hope you are doing well. I need your help in developing a Matlab model for the modeling and simulation of the energy and environmental performance of an improved stove (furnace) for the combustion of charcoal briquettes (biochar). I would really appreciate your assistance.
Thank you very much.
Hi! I am using F28379D DSP. I would like to generate 20khz and 50% duty cycle. I have use ADC with the input 3Vac from voltage sensor. The TBPRD set is 2500 and the CMP value is 1250 with prescaler 1. EPWM1A and EPWM 1B are utilised in this case. Unfortunately EPWM1A duty cycle is shifting/moving/not in phase, EPWM1B is constantly producing 20khz. I am using updown counter. CAU is set CAD is Clear same goes to EPWM1B. Why this happen? I would like to do a switching where PWM 20khz is on during positive half cycle, PWM 20khz is off during negative half cycle. Appreciate for the help!
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 个投票