/matlabcentral/discussions/channelsChannels Discussions2024-07-21T02:51:11Ztag:ch.mathworks.com,2005:Topic/8698932024-07-13T06:25:53Z2024-07-13T14:31:05ZMore easily enable CAD-like view mode<p>Something that had bothered me ever since I became an FEA analyst (2012) was the apparent inability of the "camera" in Matlab's 3D plot to function like the "cameras" in CAD/CAE packages.
For instance, load the ForearmLink.stl model that ships with the PDE Toolbox in Matlab and ParaView and try rotating the model.
clear
close all
gm = importGeometry( "ForearmLink.stl" );
pdegplot(gm)</p><p>To provide talking points, here's a YouTube video I recorded.
Things to observe:
Note that I cant seem to rotate continuously around the x-axis. It appears to only support rotations from [0, 360] as opposed to [-inf, inf]. So, for example, if I'm looking in the Y+ direction and rotate around X so that I'm looking at the Z- direction, and then want to look in the Y- direction, I can't simply keep rotating around the X axis... instead have to rotate 180 degrees around the Z axis and then around the X axis. I'm not aware of any data visualization applications (e.g., ParaView, VisIt, EnSight) or CAD/CAE tools with such an interaction.
Note that at the 50 second mark, I set a view in ParaView: looking in the [X-, Y-, Z-] direction with Y+ up. Try as I might in Matlab, I'm unable to achieve that same view perspective.
Today I discovered that if one turns on the Camera Toolbar from the View menubar, then clicks the Orbit Camera icon, then the No Principal Axis icon:</p><p>That then it acts in the manner I've long desired. Oh, and also, for the interested, it is programmatically available: https://www.mathworks.com/help/matlab/ref/cameratoolbar.html
I might humbly propose this mode either be made more discoverable, similar to the little interaction widgets that pop up in figures:</p><p>Or maybe use the middle-mouse button to temporarily use this mode (a mouse setting in, e.g., Abaqus/CAE).</p>Gregory Vernonhttps://ch.mathworks.com/matlabcentral/profile/authors/14170832tag:ch.mathworks.com,2005:Topic/8693332024-07-09T22:11:17Z2024-07-18T17:03:27ZMatlab Custom Font<p>I've noticed is that the highly rated fonts for coding (e.g. Fira Code, Inconsolata, etc.) seem to overlook one issue that is key for coding in Matlab. While these fonts make 0 and O, as well as the 1 and l easily distinguishable, the brackets are not. Quite often the curly bracket looks similar to the curved bracket, which can lead to mistakes when coding or reviewing code.
So I was thinking: Could Mathworks put together a team to review good programming fonts, and come up with their own custom font designed specifically and optimized for Matlab syntax?</p>Honzikhttps://ch.mathworks.com/matlabcentral/profile/authors/219831tag:ch.mathworks.com,2005:Topic/8690112024-07-07T20:34:22Z2024-07-09T18:48:38ZRequest for Assistance with Calculating Controller Gain Values<p>could you explain me how to calculate the gain values for different types of controllers (Conventional Sliding Mode Control, Third Order Sliding Mode Control, Variable Gain Super Twisting Algorithm.
Could you, assist me in providing a mathematical method, for example, to calculate the gains of the above-mentioned controllers?
Thank you
M. Itouchene</p>itouchenehttps://ch.mathworks.com/matlabcentral/profile/authors/28540679tag:ch.mathworks.com,2005:Topic/8688312024-07-05T17:56:04Z2024-07-14T04:24:52ZNeed help to get started with matlab<p>Hello everyone, i hope you all are in good health. i need to ask you about the help about where i should start to get indulge in matlab. I am an electrical engineer but having experience of construction field. I am new here. Please do help me. I shall be waiting forward to hear from you. I shall be grateful to you. Need recommendations and suggestions from experienced members. Thank you.</p>Muhammadhttps://ch.mathworks.com/matlabcentral/profile/authors/34384838tag:ch.mathworks.com,2005:Topic/8683862024-07-02T13:01:53Z2024-07-02T13:01:53Zdocument on solving ODEs and PDEs<p>I recently wrote up a document which addresses the solution of ordinary and partial differential equations in Matlab (with some Python examples thrown in for those who are interested). For ODEs, both initial and boundary value problems are addressed. For PDEs, it addresses parabolic and elliptic equations. The emphasis is on finite difference approaches and built-in functions are discussed when available. Theory is kept to a minimum. I also provide a discussion of strategies for checking the results, because I think many students are too quick to trust their solutions. For anyone interested, the document can be found at https://blanchard.neep.wisc.edu/SolvingDifferentialEquationsWithMatlab.pdf</p>James Blanchardhttps://ch.mathworks.com/matlabcentral/profile/authors/6002112tag:ch.mathworks.com,2005:Topic/8678962024-06-26T20:41:34Z2024-06-26T20:41:34ZGeometry-Based Stochastic Channel Modeling<p>Kindly link me to the Channel Modeling Group.
I read and compreheneded a paper on channel modeling "An Adaptive Geometry-Based Stochastic Model for Non-Isotropic MIMO Mobile-to-Mobile Channels" except the graphical results obtained from the MATLAB codes. I have tried to replicate the same graphs but to no avail from my codes. And I am really interested in the topic, i have even written to the authors of the paper but as usual, there is no reply from them. Kindly assist if possible.</p>Sylvesterhttps://ch.mathworks.com/matlabcentral/profile/authors/34256763tag:ch.mathworks.com,2005:Topic/8678362024-06-26T09:32:27Z2024-06-27T13:01:01ZWhere to find coding and algorithms problems with solutions?<p>Hi, I'm looking for sites where I can find coding & algorithms problems and their solutions. I'm doing this workshop in college and I'll need some problems to go over with the students and explain how Matlab works by solving the problems with them and then reviewing and going over different solution options. Does anyone know a website like that? I've tried looking in the Matlab Cody By Mathworks, but didn't exactly find what I'm looking for. Thanks in advance.</p>Saleemhttps://ch.mathworks.com/matlabcentral/profile/authors/32773865tag:ch.mathworks.com,2005:Topic/8669212024-06-19T21:07:35Z2024-06-21T23:57:58ZAdd Tools->Basic Fitting->...Weighted least squares<p>An option for 10th degree polynomials but no weighted linear least squares. Seriously? Jesse</p>jmgoldbahttps://ch.mathworks.com/matlabcentral/profile/authors/16543328tag:ch.mathworks.com,2005:Topic/8667862024-06-19T15:23:08Z2024-06-19T16:53:22ZNVIDIA supercharge the AI world <p>What do you think about the NVIDIA's achivement of becoming the top giant of manufacturing chips, especially for AI world?</p>Kalharahttps://ch.mathworks.com/matlabcentral/profile/authors/33906775tag:ch.mathworks.com,2005:Topic/8667112024-06-18T21:19:39Z2024-07-21T02:51:11ZAsk Me Anything about image analysis or the Mathworks community<p>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.</p>Image Analysthttps://ch.mathworks.com/matlabcentral/profile/authors/1343420tag:ch.mathworks.com,2005:Topic/8664962024-06-17T14:57:15Z2024-06-17T14:57:15ZWeek of June 17th - Must-See MATLAB Central Posts<p>Hello, everyone!
Over the past few weeks, our community has been buzzing with activity, showcasing the incredible depth of knowledge, creativity, and innovation that makes this forum such a vibrant place. Today, we're excited to highlight some of the noteworthy contributions that have sparked discussions, offered insights, and shared knowledge across various topics. Let's dive in!</p><p>Interesting Questions
Proving one function is greater than other? by Fatima Majeed
Fatima Majeed brings us a thought-provoking mathematical challenge, delving into inequalities and the realms beyond (e^e). If you're up for a mathematical journey, this question is a must-see!
How to split/segment csv file into multiple sections? by lil brain
lil brain tackles a practical problem many of us have faced: efficiently segmenting a CSV file based on specific criteria. This post is not only a query but a learning opportunity for anyone dealing with similar data manipulation challenges.</p><p>Popular Discussions
Trick: Easy Digit Manipulation by goc3
Discover a simple yet effective trick for digit manipulation from goc3. This tip is especially handy for those frequenting Cody challenges or anyone interested in enhancing their number handling skills in MATLAB.
Run Code in Discussions Area! by Chen Lin
Chen Lin shares an exciting update about the 'Run Code' feature in the Discussions area, highlighting how our community can now directly execute and share code snippets within discussions. This feature marks a significant enhancement in how we interact and solve problems together.</p><p>From the Blogs
A Deep Dive into EEG Analysis for Predicting Neurological Outcomes By Tanya Kuruvilla
Connell D`Souza, alongside Team Swarthbeat, explores the cutting-edge application of EEG analysis in predicting neurological outcomes post-cardiac arrest. This blog post offers an in-depth look into the challenges and methodologies of modern medical data analysis.
Crafting the Robots of Tomorrow: The Power of Robot Simulation with MATLAB and Simulink by YJ Lim
Mihir Acharya discusses the pivotal role of MATLAB and Simulink in the future of robotics simulation. Through an engaging conversation with industry analyst George Chowdhury, this post sheds light on overcoming simulation challenges and the exciting possibilities that lie ahead.</p><p>We encourage everyone to explore these contributions further and engage with the authors and the community. Your participation is what fuels this community's continual growth and innovation.
Here's to many more discussions, discoveries, and breakthroughs together!</p>Davidhttps://ch.mathworks.com/matlabcentral/profile/authors/4480925tag:ch.mathworks.com,2005:Topic/8664112024-06-16T23:28:03Z2024-07-04T03:12:44ZStochastic simulation of a novel pathogen<p>We are modeling the introduction of a novel pathogen into a completely susceptible population. In the cells below, I have provided you with the Matlab code for a simple stochastic SIR model, implemented using the "GillespieSSA" function</p><p>Simulating the stochastic model 100 times for
Since is 0.4 per day, per day
% Define the parameters
beta = 0.36;
gamma = 0.4;
n_sims = 100;
tf = 100; % Time frame changed to 100</p><p>% Calculate R0
R0 = beta / gamma</p><p>% Initial state values
initial_state_values = [1000000; 1; 0; 0]; % S, I, R, cum_inc</p><p>% Define the propensities and state change matrix
a = @(state) [beta * state(1) * state(2) / 1000000, gamma * state(2)];
nu = [-1, 0; 1, -1; 0, 1; 0, 0];</p><p>% Define the Gillespie algorithm function
function [t_values, state_values] = gillespie_ssa(initial_state, a, nu, tf)
t = 0;
state = initial_state(:); % Ensure state is a column vector
t_values = t;
state_values = state';</p><pre> while t < tf
rates = a(state);
rate_sum = sum(rates);
if rate_sum == 0
break;
end</pre><pre> tau = -log(rand) / rate_sum;
t = t + tau;</pre><pre> r = rand * rate_sum;
cum_sum_rates = cumsum(rates);
reaction_index = find(cum_sum_rates >= r, 1);</pre><pre> state = state + nu(:, reaction_index);</pre><pre> % Update cumulative incidence if infection occurred
if reaction_index == 1
state(4) = state(4) + 1; % Increment cumulative incidence
end</pre><pre> t_values = [t_values; t];
state_values = [state_values; state'];
end
end</pre><p>% Function to simulate the stochastic model multiple times and plot results
function simulate_stoch_model(beta, gamma, n_sims, tf, initial_state_values, R0, plot_type)
% Define the propensities and state change matrix
a = @(state) [beta * state(1) * state(2) / 1000000, gamma * state(2)];
nu = [-1, 0; 1, -1; 0, 1; 0, 0];</p><pre> % Set random seed for reproducibility
rng(11);</pre><pre> % Initialize plot
figure;
hold on;</pre><pre> for i = 1:n_sims
[t, output] = gillespie_ssa(initial_state_values, a, nu, tf);</pre><pre> % Check if the simulation had only one step and re-run if necessary
while length(t) == 1
[t, output] = gillespie_ssa(initial_state_values, a, nu, tf);
end</pre><pre> if strcmp(plot_type, 'cumulative_incidence')
plot(t, output(:, 4), 'LineWidth', 2, 'Color', rand(1, 3));
elseif strcmp(plot_type, 'prevalence')
plot(t, output(:, 2), 'LineWidth', 2, 'Color', rand(1, 3));
end
end</pre><pre> xlabel('Time (days)');</pre><pre> if strcmp(plot_type, 'cumulative_incidence')
ylabel('Cumulative Incidence');
ylim([0 inf]);
elseif strcmp(plot_type, 'prevalence')
ylabel('Prevalence of Infection');
ylim([0 50]);
end</pre><pre> title(['Stochastic model output for R0 = ', num2str(R0)]);
subtitle([num2str(n_sims), ' simulations']);
xlim([0 tf]);
grid on;
hold off;
end</pre><p>% Simulate the model 100 times and plot cumulative incidence
simulate_stoch_model(beta, gamma, n_sims, tf, initial_state_values, R0, 'cumulative_incidence');</p><p>% Simulate the model 100 times and plot prevalence
simulate_stoch_model(beta, gamma, n_sims, tf, initial_state_values, R0, 'prevalence');</p>Athanasios Paraskevopouloshttps://ch.mathworks.com/matlabcentral/profile/authors/30623616tag:ch.mathworks.com,2005:Topic/8660362024-06-13T20:22:47Z2024-06-13T20:22:47ZMake a video: "How I Solved It"<p>Twitch built an entire business around letting you watch over someone's shoulder while they play video games. I feel like we should be able to make at least a few videos where we get to watch over someone's shoulder while they solve Cody problems. I would pay good money for a front-row seat to watch some of my favorite solvers at work. Like, I want to know, did Alfonso Nieto-Castonon just sit down and bang out some of those answers, or did he have to think about it for a while? What was he thinking about while he solved it? What resources was he drawing on? There's nothing like watching a master craftsman at work.
I can imagine a whole category of Cody videos called "How I Solved It". I tried making one of these myself a while back, but as far as I could tell, nobody else made one.
https://blogs.mathworks.com/community/2015/02/26/lets-code-make-a-cody-video/
Here's the direct link to the video: https://www.youtube.com/watch?v=hoSmO1XklAQ
I hereby challenge you to make a "How I Solved It" video and post it here. If you make one, I'll make another one.</p>Ned Gulleyhttps://ch.mathworks.com/matlabcentral/profile/authors/140947tag:ch.mathworks.com,2005:Topic/8660312024-06-13T19:18:16Z2024-07-19T15:22:05Z+1 for Backwards Loops!<p>Base case:
Suppose you need to do a computation many times. We are going to assume that this computation cannot be vectorized. The simplest case is to use a for loop:
number_of_elements = 1e6;
test_fcn = @(x) sqrt(x) / x;
tic
for i = 1:number_of_elements
x(i) = test_fcn(i);
end
t_forward = toc;
disp(t_forward + " seconds")
Preallocation:
This can easily be sped up by preallocating the variable that houses results:
tic
x = zeros(number_of_elements, 1);
for i = 1:number_of_elements
x(i) = test_fcn(i);
end
t_forward_prealloc = toc;
disp(t_forward_prealloc + " seconds")
In this example, preallocation speeds up the loop by a factor of about three to four (running in R2024a). Comment below if you get dramatically different results.
disp(sprintf("%.1f", t_forward / t_forward_prealloc))
Run it in reverse:
Is there a way to skip the explicit preallocation and still be fast? Indeed, there is.
clear x
tic
for i = number_of_elements:-1:1
x(i) = test_fcn(i);
end
t_backward = toc;
disp(t_backward + " seconds")
By running the loop backwards, the preallocation is implicitly performed during the first iteration and the loop runs in about the same time (within statistical noise):
disp(sprintf("%.2f", t_forward_prealloc / t_backward))
Do you get similar results when running this code? Let us know your thoughts in the comments below.
Beneficial side effect:
Have you ever had to use a for loop to delete elements from a vector? If so, keeping track of index offsets can be tricky, as deleting any element shifts all those that come after. By running the for loop in reverse, you don't need to worry about index offsets while deleting elements.</p>goc3https://ch.mathworks.com/matlabcentral/profile/authors/5349647tag:ch.mathworks.com,2005:Topic/8660262024-06-13T18:18:36Z2024-06-14T13:50:52ZRun Code in Discussions Area!<p>We're thrilled to share an exciting update with our community: the 'Run Code' feature is now available in the Discussions area!
Simply insert your code into the editor and press the green triangle button to run it. Your code will execute using the latest MATLAB R24a version, and it supports most common toolboxes. Moreover, this innovative feature allows for the running of attached files, further enhancing its utility and flexibility.</p><p>The ‘run code’ feature was first introduced in MATLAB Answers. Encouraged by the positive feedback and at the request of our community members, we are now expanding the availability of this feature to more areas within our community.
As always, your feedback is crucial to us, so please don't hesitate to share your thoughts and experiences by leaving a comment.</p>Chen Linhttps://ch.mathworks.com/matlabcentral/profile/authors/6682740tag:ch.mathworks.com,2005:Topic/8657362024-06-11T20:27:42Z2024-06-25T16:31:34ZWhat's your opinion of the Ans Hack?<p>The Ans Hack is a dubious way to shave a few points off your solution score. Instead of a standard answer like this
function y = times_two(x)
y = 2*x;
end
you would do this
function ans = times_two(x)
2*x;
end
The ans variable is automatically created when there is no left-hand side to an evaluated expression. But it makes for an ugly function. I don't think anyone actually defends it as a good practice. The question I would ask is: is it so offensive that it should be specifically disallowed by the rules? Or is it just one of many little hacks that you see in Cody, inelegant but tolerable in the context of the surrounding game?
Incidentally, I wrote about the Ans Hack long ago on the Community Blog. Dealing with user-unfriendly code is also one of the reasons we created the Head-to-Head voting feature. Some techniques are good for your score, and some are good for your code readability. You get to decide with you care about.</p>Ned Gulleyhttps://ch.mathworks.com/matlabcentral/profile/authors/140947tag:ch.mathworks.com,2005:Topic/8654562024-06-09T16:52:55Z2024-06-09T23:07:21ZHow to set the AlphaData of a colorbar?<p>Many times when ploting, we not only need to set the color of the plot, but also its
transparency, Then how we set the alphaData of colorbar at the same time ?</p><p>It seems easy to do so :
data = rand(12,12);
% Transparency range 0-1, .3-1 for better appearance here
AData = rescale(- data, .3, 1);</p><p>% Draw an imagesc with numerical control over colormap and transparency
imagesc(data, 'AlphaData',AData);
colormap(jet);</p><p>ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';</p><p>% get colorbar object
CBarHdl = colorbar;
pause(1e-16)
% Modify the transparency of the colorbar
CData = CBarHdl.Face.Texture.CData;
ALim = [min(min(AData)), max(max(AData))];
CData(4,:) = uint8(255.*rescale(1:size(CData, 2), ALim(1), ALim(2)));
CBarHdl.Face.Texture.ColorType = 'TrueColorAlpha';
CBarHdl.Face.Texture.CData = CData;
But !!!!!!!!!!!!!!! We cannot preserve the changes when saving them as images ：</p><p>It seems that when saving plots, the `Texture` will be refresh, but the `Face` will not :
however, object Face only have 4 colors to change(The four corners of a quadrilateral), how
can we set more colors ??</p><p>`Face` is a quadrilateral object, and we can change the `VertexData` to draw more than one little quadrilaterals:
data = rand(12,12);
% Transparency range 0-1, .3-1 for better appearance here
AData = rescale(- data, .3, 1);</p><p>%Draw an imagesc with numerical control over colormap and transparency
imagesc(data, 'AlphaData',AData);
colormap(jet);</p><p>ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';</p><p>% get colorbar object
CBarHdl = colorbar;
pause(1e-16)
% Modify the transparency of the colorbar
CData = CBarHdl.Face.Texture.CData;
ALim = [min(min(AData)), max(max(AData))];
CData(4,:) = uint8(255.*rescale(1:size(CData, 2), ALim(1), ALim(2)));</p><p>warning off
CBarHdl.Face.ColorType = 'TrueColorAlpha';
VertexData = CBarHdl.Face.VertexData;
tY = repmat((1:size(CData,2))./size(CData,2), [4,1]);
tY1 = tY(:).'; tY2 = tY - tY(1,1); tY2(3:4,:) = 0; tY2 = tY2(:).';
tM1 = [tY1.*0 + 1; tY1; tY1.*0 + 1];
tM2 = [tY1.*0; tY2; tY1.*0];
CBarHdl.Face.VertexData = repmat(VertexData, [1,size(CData,2)]).*tM1 + tM2;
CBarHdl.Face.ColorData = reshape(repmat(CData, [4,1]), 4, []);</p><p>The higher the value, the more transparent it becomes
data = rand(12,12);
AData = rescale(- data, .3, 1);</p><p>imagesc(data, 'AlphaData',AData);
colormap(jet);</p><p>ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';</p><p>CBarHdl = colorbar;
pause(1e-16)
CData = CBarHdl.Face.Texture.CData;
ALim = [min(min(AData)), max(max(AData))];
CData(4,:) = uint8(255.*rescale(size(CData, 2):-1:1, ALim(1), ALim(2)));</p><p>warning off
CBarHdl.Face.ColorType = 'TrueColorAlpha';
VertexData = CBarHdl.Face.VertexData;
tY = repmat((1:size(CData,2))./size(CData,2), [4,1]);
tY1 = tY(:).'; tY2 = tY - tY(1,1); tY2(3:4,:) = 0; tY2 = tY2(:).';
tM1 = [tY1.*0 + 1; tY1; tY1.*0 + 1];
tM2 = [tY1.*0; tY2; tY1.*0];
CBarHdl.Face.VertexData = repmat(VertexData, [1,size(CData,2)]).*tM1 + tM2;
CBarHdl.Face.ColorData = reshape(repmat(CData, [4,1]), 4, []);</p><p>More transparent in the middle
data = rand(12,12) - .5;
AData = rescale(abs(data), .1, .9);</p><p>imagesc(data, 'AlphaData',AData);
colormap(jet);</p><p>ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';</p><p>CBarHdl = colorbar;
pause(1e-16)
CData = CBarHdl.Face.Texture.CData;
ALim = [min(min(AData)), max(max(AData))];
CData(4,:) = uint8(255.*rescale(abs((1:size(CData, 2)) - (1 + size(CData, 2))/2), ALim(1), ALim(2)));</p><p>warning off
CBarHdl.Face.ColorType = 'TrueColorAlpha';
VertexData = CBarHdl.Face.VertexData;
tY = repmat((1:size(CData,2))./size(CData,2), [4,1]);
tY1 = tY(:).'; tY2 = tY - tY(1,1); tY2(3:4,:) = 0; tY2 = tY2(:).';
tM1 = [tY1.*0 + 1; tY1; tY1.*0 + 1];
tM2 = [tY1.*0; tY2; tY1.*0];
CBarHdl.Face.VertexData = repmat(VertexData, [1,size(CData,2)]).*tM1 + tM2;
CBarHdl.Face.ColorData = reshape(repmat(CData, [4,1]), 4, []);</p><p>The code will work if the plot have AlphaData property
data = peaks(30);
AData = rescale(data, .2, 1);</p><p>surface(data, 'FaceAlpha','flat','AlphaData',AData);
colormap(jet(100));</p><p>ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';
view(3)</p><p>CBarHdl = colorbar;
pause(1e-16)
CData = CBarHdl.Face.Texture.CData;
ALim = [min(min(AData)), max(max(AData))];
CData(4,:) = uint8(255.*rescale(1:size(CData, 2), ALim(1), ALim(2)));</p><p>warning off
CBarHdl.Face.ColorType = 'TrueColorAlpha';
VertexData = CBarHdl.Face.VertexData;
tY = repmat((1:size(CData,2))./size(CData,2), [4,1]);
tY1 = tY(:).'; tY2 = tY - tY(1,1); tY2(3:4,:) = 0; tY2 = tY2(:).';
tM1 = [tY1.*0 + 1; tY1; tY1.*0 + 1];
tM2 = [tY1.*0; tY2; tY1.*0];
CBarHdl.Face.VertexData = repmat(VertexData, [1,size(CData,2)]).*tM1 + tM2;
CBarHdl.Face.ColorData = reshape(repmat(CData, [4,1]), 4, []);</p>Zhaoxu Liu / slandarerhttps://ch.mathworks.com/matlabcentral/profile/authors/18192500tag:ch.mathworks.com,2005:Topic/8654512024-06-09T16:21:08Z2024-06-09T16:21:08ZDiscovering an Excellent Resource on Ordinary Differential Equations<p>While searching the internet for some books on ordinary differential equations, I came across a link that I believe is very useful for all math students and not only. If you are interested in ODEs, it's worth taking the time to study it.
A First Look at Ordinary Differential Equations by Timothy S. Judson is an excellent resource for anyone looking to understand ODEs better. Here's a brief overview of the main topics covered:
Introduction to ODEs: Basic concepts, definitions, and initial differential equations.
Methods of Solution:
Separable equations
First-order linear equations
Exact equations
Transcendental functions
Applications of ODEs: Practical examples and applications in various scientific fields.
Systems of ODEs: Analysis and solutions of systems of differential equations.
Series and Numerical Methods: Use of series and numerical methods for solving ODEs.
This book provides a clear and comprehensive introduction to ODEs, making it suitable for students and new researchers in mathematics. If you're interested, you can explore the book in more detail here: A First Look at Ordinary Differential Equations.</p>Athanasios Paraskevopouloshttps://ch.mathworks.com/matlabcentral/profile/authors/30623616tag:ch.mathworks.com,2005:Topic/8652162024-06-06T17:52:29Z2024-06-06T17:52:29ZNumerical Simulation of the Discrete Klein-Gordon Equation: A Study on Damped, Driven Nonlinear Wave Systems with Spatially Extended Initial Conditions<p>The study of the dynamics of the discrete Klein - Gordon equation (DKG) with friction is given by the equation :</p><p>In the above equation, W describes the potential function:
to which every coupled unit adheres. In Eq. (1), the variable $$ is the unknown displacement of the oscillator occupying the n-th position of the lattice, and is the discretization parameter. We denote by h the distance between the oscillators of the lattice. The chain (DKG) contains linear damping with a damping coefficient , whileis the coefficient of the nonlinear cubic term.</p><p>For the DKG chain (1), we will consider the problem of initial-boundary values, with initial conditions</p><p>and Dirichlet boundary conditions at the boundary points and , that is,</p><p>Therefore, when necessary, we will use the short notation for the one-dimensional discrete Laplacian</p><p>Now we want to investigate numerically the dynamics of the system (1)-(2)-(3). Our first aim is to conduct a numerical study of the property of Dynamic Stability of the system, which directly depends on the existence and linear stability of the branches of equilibrium points.</p><p>For the discussion of numerical results, it is also important to emphasize the role of the parameter . By changing the time variable , we rewrite Eq. (1) in the form</p><p>. We consider spatially extended initial conditions of the form: where is the distance of the grid and is the amplitude of the initial condition</p><p>We also assume zero initial velocity:</p><pre> the following graphs for and
% Parameters
L = 200; % Length of the system
K = 99; % Number of spatial points
j = 2; % Mode number
omega_d = 1; % Characteristic frequency
beta = 1; % Nonlinearity parameter
delta = 0.05; % Damping coefficient</pre><p>% Spatial grid
h = L / (K + 1);
n = linspace(-L/2, L/2, K+2); % Spatial points
N = length(n);
omegaDScaled = h * omega_d;
deltaScaled = h * delta;</p><p>% Time parameters
dt = 1; % Time step
tmax = 3000; % Maximum time
tspan = 0:dt:tmax; % Time vector</p><p>% Values of amplitude 'a' to iterate over
a_values = [2, 1.95, 1.9, 1.85, 1.82]; % Modify this array as needed</p><p>% Differential equation solver function
function dYdt = odefun(~, Y, N, h, omegaDScaled, deltaScaled, beta)
U = Y(1:N);
Udot = Y(N+1:end);
Uddot = zeros(size(U));</p><pre> % Laplacian (discrete second derivative)
for k = 2:N-1
Uddot(k) = (U(k+1) - 2 * U(k) + U(k-1)) ;
end</pre><pre> % System of equations
dUdt = Udot;
dUdotdt = Uddot - deltaScaled * Udot + omegaDScaled^2 * (U - beta * U.^3);</pre><pre> % Pack derivatives
dYdt = [dUdt; dUdotdt];
end</pre><p>% Create a figure for subplots
figure;</p><p>% Initial plot
a_init = 2; % Example initial amplitude for the initial condition plot
U0_init = a_init * sin((j * pi * h * n) / L); % Initial displacement
U0_init(1) = 0; % Boundary condition at n = 0
U0_init(end) = 0; % Boundary condition at n = K+1
subplot(3, 2, 1);
plot(n, U0_init, 'r.-', 'LineWidth', 1.5, 'MarkerSize', 10); % Line and marker plot
xlabel('$x_n$', 'Interpreter', 'latex');
ylabel('$U_n$', 'Interpreter', 'latex');
title('$t=0$', 'Interpreter', 'latex');
set(gca, 'FontSize', 12, 'FontName', 'Times');
xlim([-L/2 L/2]);
ylim([-3 3]);
grid on;</p><p>% Loop through each value of 'a' and generate the plot
for i = 1:length(a_values)
a = a_values(i);</p><pre> % Initial conditions
U0 = a * sin((j * pi * h * n) / L); % Initial displacement
U0(1) = 0; % Boundary condition at n = 0
U0(end) = 0; % Boundary condition at n = K+1
Udot0 = zeros(size(U0)); % Initial velocity</pre><pre> % Pack initial conditions
Y0 = [U0, Udot0];</pre><pre> % Solve ODE
opts = odeset('RelTol', 1e-5, 'AbsTol', 1e-6);
[t, Y] = ode45(@(t, Y) odefun(t, Y, N, h, omegaDScaled, deltaScaled, beta), tspan, Y0, opts);</pre><pre> % Extract solutions
U = Y(:, 1:N);
Udot = Y(:, N+1:end);</pre><pre> % Plot final displacement profile
subplot(3, 2, i+1);
plot(n, U(end,:), 'b.-', 'LineWidth', 1.5, 'MarkerSize', 10); % Line and marker plot
xlabel('$x_n$', 'Interpreter', 'latex');
ylabel('$U_n$', 'Interpreter', 'latex');
title(['$t=3000$, $a=', num2str(a), '$'], 'Interpreter', 'latex');
set(gca, 'FontSize', 12, 'FontName', 'Times');
xlim([-L/2 L/2]);
ylim([-2 2]);
grid on;
end</pre><p>% Adjust layout
set(gcf, 'Position', [100, 100, 1200, 900]); % Adjust figure size as needed</p><p>Dynamics for the initial condition , , for , for different amplitude values. By reducing the amplitude values, we observe the convergence to equilibrium points of different branches from and the appearance of values for which the solution converges to a non-linear equilibrium point Parameters:</p><pre> Detection of a stability threshold : For , the initial condition , , converges to a non-linear equilibrium point.</pre><p>Characteristics for , with corresponding norm where the dynamics appear in the first image of the third row, we observe convergence to a non-linear equilibrium point of branch This has the same norm and the same energy as the previous case but the final state has a completely different profile. This result suggests secondary bifurcations have occurred in branch</p><p>By further reducing the amplitude, distinct values of are discerned: 1.9, 1.85, 1.81 for which the initial condition with norms respectively, converges to a non-linear equilibrium point of branch This equilibrium point has norm and energy . The behavior of this equilibrium is illustrated in the third row and in the first image of the third row of Figure 1, and also in the first image of the third row of Figure 2. For all the values between the aforementioned , the initial condition converges to geometrically different non-linear states of branch as shown in the second image of the first row and the first image of the second row of Figure 2, for amplitudes and respectively.</p><p>Refference:
Dynamics of nonlinear lattices: asymptotic behavior and study of the existence and stability of tracked oscillations-Vetas Konstantinos (2018)</p>Athanasios Paraskevopouloshttps://ch.mathworks.com/matlabcentral/profile/authors/30623616tag:ch.mathworks.com,2005:Topic/8650412024-06-05T18:12:11Z2024-06-13T22:12:34ZIntroducing a New Discussions Area for Cody Users!<p>Many MATLAB enthusiasts come Cody to sharpen their skills, face new challenges, and engage in friendly competition. We firmly believe that learning from peers is one of the most effective ways to grow.
With this in mind, the Cody team is thrilled to unveil a new feature aimed at enriching your learning journey: the Cody Discussion Channel. This space is designed for sharing expertise, acquiring new skills, and fostering connections within our community.
On the Cody homepage, you'll now notice a Discussions section, prominently displaying the four most recent posts. For those eager to contribute, we encourage you to familiarize yourself with our posting guidelines before creating a new post. This will help maintain a constructive and valuable exchange of ideas for everyone involved.</p><p>Together, let's create an environment where every member feels empowered to share, learn, and connect.</p>Chen Linhttps://ch.mathworks.com/matlabcentral/profile/authors/6682740