主要内容

Results for


goc3
goc3
Last activity 2024-9-8,14:47

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")
0.10925 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")
0.035106 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))
3.1
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")
0.032392 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))
1.08
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.
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.
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 ?
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);
% Draw an imagesc with numerical control over colormap and transparency
imagesc(data, 'AlphaData',AData);
colormap(jet);
ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';
% 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 :
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 ??
`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);
%Draw an imagesc with numerical control over colormap and transparency
imagesc(data, 'AlphaData',AData);
colormap(jet);
ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';
% 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)));
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, []);
The higher the value, the more transparent it becomes
data = rand(12,12);
AData = rescale(- data, .3, 1);
imagesc(data, 'AlphaData',AData);
colormap(jet);
ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';
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)));
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, []);
More transparent in the middle
data = rand(12,12) - .5;
AData = rescale(abs(data), .1, .9);
imagesc(data, 'AlphaData',AData);
colormap(jet);
ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';
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)));
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, []);
The code will work if the plot have AlphaData property
data = peaks(30);
AData = rescale(data, .2, 1);
surface(data, 'FaceAlpha','flat','AlphaData',AData);
colormap(jet(100));
ax = gca;
ax.DataAspectRatio = [1,1,1];
ax.TickDir = 'out';
ax.Box = 'off';
view(3)
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)));
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, []);
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:
  1. Introduction to ODEs: Basic concepts, definitions, and initial differential equations.
  2. Methods of Solution:
  • Separable equations
  • First-order linear equations
  • Exact equations
  • Transcendental functions
  1. Applications of ODEs: Practical examples and applications in various scientific fields.
  2. Systems of ODEs: Analysis and solutions of systems of differential equations.
  3. 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.
The study of the dynamics of the discrete Klein - Gordon equation (DKG) with friction is given by the equation :
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.
For the DKG chain (1), we will consider the problem of initial-boundary values, with initial conditions
and Dirichlet boundary conditions at the boundary points and , that is,
Therefore, when necessary, we will use the short notation for the one-dimensional discrete Laplacian
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.
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
. We consider spatially extended initial conditions of the form: where is the distance of the grid and is the amplitude of the initial condition
We also assume zero initial velocity:
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
% 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;
% Time parameters
dt = 1; % Time step
tmax = 3000; % Maximum time
tspan = 0:dt:tmax; % Time vector
% Values of amplitude 'a' to iterate over
a_values = [2, 1.95, 1.9, 1.85, 1.82]; % Modify this array as needed
% 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));
% Laplacian (discrete second derivative)
for k = 2:N-1
Uddot(k) = (U(k+1) - 2 * U(k) + U(k-1)) ;
end
% System of equations
dUdt = Udot;
dUdotdt = Uddot - deltaScaled * Udot + omegaDScaled^2 * (U - beta * U.^3);
% Pack derivatives
dYdt = [dUdt; dUdotdt];
end
% Create a figure for subplots
figure;
% 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;
% Loop through each value of 'a' and generate the plot
for i = 1:length(a_values)
a = a_values(i);
% 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
% Pack initial conditions
Y0 = [U0, Udot0];
% 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);
% Extract solutions
U = Y(:, 1:N);
Udot = Y(:, N+1:end);
% 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
% Adjust layout
set(gcf, 'Position', [100, 100, 1200, 900]); % Adjust figure size as needed
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:
Detection of a stability threshold : For , the initial condition , , converges to a non-linear equilibrium point.
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
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 a, 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.
Refference:
  1. Dynamics of nonlinear lattices: asymptotic behavior and study of the existence and stability of tracked oscillations-Vetas Konstantinos (2018)
There are a host of problems on Cody that require manipulation of the digits of a number. Examples include summing the digits of a number, separating the number into its powers, and adding very large numbers together.
If you haven't come across this trick yet, you might want to write it down (or save it electronically):
digits = num2str(4207) - '0'
That code results in the following:
digits =
4 2 0 7
Now, summing the digits of the number is easy:
sum(digits)
ans =
13
Hello and a warm welcome to everyone! We're excited to have you in the Cody Discussion Channel. To ensure the best possible experience for everyone, it's important to understand the types of content that are most suitable for this channel.
Content that belongs in the Cody Discussion Channel:
  • Tips & tricks: Discuss strategies for solving Cody problems that you've found effective.
  • Ideas or suggestions for improvement: Have thoughts on how to make Cody better? We'd love to hear them.
  • Issues: Encountering difficulties or bugs with Cody? Let us know so we can address them.
  • Requests for guidance: Stuck on a Cody problem? Ask for advice or hints, but make sure to show your efforts in attempting to solve the problem first.
  • General discussions: Anything else related to Cody that doesn't fit into the above categories.
Content that does not belong in the Cody Discussion Channel:
  • Comments on specific Cody problems: Examples include unclear problem descriptions or incorrect testing suites.
  • Comments on specific Cody solutions: For example, you find a solution creative or helpful.
Please direct such comments to the Comments section on the problem or solution page itself.
We hope the Cody discussion channel becomes a vibrant space for sharing expertise, learning new skills, and connecting with others.
Hans Scharler
Hans Scharler
Last activity 2024-5-31

Spring is here in Natick and the tulips are blooming! While tulips appear only briefly here in Massachusetts, they provide a lot of bright and diverse colors and shapes. To celebrate this cheerful flower, here's some code to create your own tulip!
Check out this episode about PIVLab: https://www.buzzsprout.com/2107763/15106425
Join the conversation with William Thielicke, the developer of PIVlab, as he shares insights into the world of particle image velocimetery (PIV) and its applications. Discover how PIV accurately measures fluid velocities, non invasively revolutionising research across the industries. Delve into the development journey of PI lab, including collaborations, key features and future advancements for aerodynamic studies, explore the advanced hardware setups camera technologies, and educational prospects offered by PIVlab, for enhanced fluid velocity measurements. If you are interested in the hardware he speaks of check out the company: Optolution.
One of the starter prompts is about rolling two six-sided dice and plot the results. As a hobby, I create my own board games. I was able to use the dice rolling prompt to show how a simple roll and move game would work. That was a great surprise!
How to leave feedback on a doc page
Leaving feedback is a two-step process. At the bottom of most pages in the MATLAB documentation is a star rating.
Start by selecting a star that best answers the question. After selecting a star rating, an edit box appears where you can offer specific feedback.
When you press "Submit" you'll see the confirmation dialog below. You cannot go back and edit your content, although you can refresh the page to go through that process again.
Tips on leaving feedback
  • Be productive. The reader should clearly understand what action you'd like to see, what was unclear, what you think needs work, or what areas were really helpful.
  • Positive feedback is also helpful. By nature, feedback often focuses on suggestions for changes but it also helps to know what was clear and what worked well.
  • Point to specific areas of the page. This helps the reader to narrow the focus of the page to the area described by your feedback.
What happens to that feedback?
Before working at MathWorks I often left feedback on documentation pages but I never knew what happens after that. One day in 2021 I shared my speculation on the process:
> That feedback is received by MathWorks Gnomes which are never seen nor heard but visit the MathWorks documentation team at night while they are sleeping and whisper selected suggestions into their ears to manipulate their dreams. Occassionally this causes them to wake up with a Eureka moment that leads to changes in the documentation.
I'd like to let you in on the secret which is much less fanciful. Feedback left in the star rating and edit box are collected and periodically reviewed by the doc writers who look for trends on highly trafficked pages and finer grain feedback on less visited pages. Your feedback is important and often results in improvements.
Oleksandr
Oleksandr
Last activity 2024-5-28

Let's talk about probability theory in Matlab.
Conditions of the problem - how many more letters do I need to write to the sales department to get an answer?
To get closer to the problem, I need to buy a license under a contract. Maybe sometimes there are responsible employees sitting here who will give me an answer.
Thank you
In the MATLAB description of the algorithm for Lyapunov exponents, I believe there is ambiguity and misuse.
The lambda(i) in the reference literature signifies the Lyapunov exponent of the entire phase space data after expanding by i time steps, but in the calculation formula provided in the MATLAB help documentation, Y_(i+K) represents the data point at the i-th point in the reconstructed data Y after K steps, and this calculation formula also does not match the calculation code given by MATLAB. I believe there should be some misguidance and misunderstanding here.
According to the symbol regulations in the algorithm description and the MATLAB code, I think the correct formula might be y(i) = 1/dt * 1/N * sum_j( log( ||Y_(j+i) - Y_(j*+i)|| ) )
Drumlin Farm has welcomed MATLAMB, named in honor of MathWorks, among ten adorable new lambs this season!
📚 New Book Announcement: "Image Processing Recipes in MATLAB" 📚
I am delighted to share the release of my latest book, "Image Processing Recipes in MATLAB," co-authored by my dear friend and colleague Gustavo Benvenutti Borba.
This 'cookbook' contains 30 practical recipes for image processing, ranging from foundational techniques to recently published algorithms. It serves as a concise and readable reference for quickly and efficiently deploying image processing pipelines in MATLAB.
Gustavo and I are immensely grateful to the MathWorks Book Program for their support. We also want to thank Randi Slack and her fantastic team at CRC Press for their patience, expertise, and professionalism throughout the process.
___________
David
David
Last activity 2024-5-23

A colleague said that you can search the Help Center using the phrase 'Introduced in' followed by a release version. Such as, 'Introduced in R2022a'. Doing this yeilds search results specific for that release.
Seems pretty handy so I thought I'd share.
Are you local to Boston?
Shape the Future of MATLAB: Join MathWorks' UX Night In-Person!
When: June 25th, 6 to 8 PM
Where: MathWorks Campus in Natick, MA
🌟 Calling All MATLAB Users! Here's your unique chance to influence the next wave of innovations in MATLAB and engineering software. MathWorks invites you to participate in our special after-hours usability studies. Dive deep into the latest MATLAB features, share your valuable feedback, and help us refine our solutions to better meet your needs.
🚀 This Opportunity Is Not to Be Missed:
  • Exclusive Hands-On Experience: Be among the first to explore new MATLAB features and capabilities.
  • Voice Your Expertise: Share your insights and suggestions directly with MathWorks developers.
  • Learn, Discover, and Grow: Expand your MATLAB knowledge and skills through firsthand experience with unreleased features.
  • Network Over Dinner: Enjoy a complimentary dinner with fellow MATLAB enthusiasts and the MathWorks team. It's a perfect opportunity to connect, share experiences, and network after work.
  • Earn Rewards: Participants will not only contribute to the advancement of MATLAB but will also be compensated for their time. Plus, enjoy special MathWorks swag as a token of our appreciation!
👉 Reserve Your Spot Now: Space is limited for these after-hours sessions. If you're passionate about MATLAB and eager to contribute to its development, we'd love to hear from you.
Bringing the beauty of MathWorks Natick's tulips to life through code!
Remix challenge: create and share with us your new breeds of MATLAB tulips!
I found this plot of words said by different characters on the US version of The Office sitcom. There's a sparkline for each character from pilot to finale episode.
Mathew
Mathew
Last activity 2024-5-16

is there any sites available online free ai course learning except: coursera.org