Pull up a chair!

Discussions is your place to get to know your peers, tackle the bigger challenges together, and have fun along the way.

  • Want to see the latest updates? Follow the Highlights!
  • Looking for techniques improve your MATLAB or Simulink skills? Tips & Tricks has you covered!
  • Sharing the perfect math joke, pun, or meme? Look no further than Fun!
  • Think there's a channel we need? Tell us more in Ideas

Newest Discussions


Check out the LLMs with MATLAB project on File Exchange to access Large Language Models from MATLAB.
Along with the latest support for GPT-4o mini, you can use LLMs with MATLAB to generate images, categorize data, and provide semantic analyis.
Run it now by clicking Open in MATLAB Online, signing in, and using your API Key from OpenAI.
function ans = your_fcn_name(n)
n;
j=sum(1:n);
a=zeros(1,j);
for i=1:n
a(1,((sum(1:(i-1))+1)):(sum(1:(i-1))+i))=i.*ones(1,i);
end
disp
Athanasios Paraskevopoulos
Athanasios Paraskevopoulos
Posted 2024년 7월 23일 15:34

Gabriel's horn is a shape with the paradoxical property that it has infinite surface area, but a finite volume.
Gabriel’s horn is formed by taking the graph of with the domain and rotating it in three dimensions about the axis.
There is a standard formula for calculating the volume of this shape, for a general function .Wwe will just state that the volume of the solid between a and b is:
The surface area of the solid is given by:
One other thing we need to consider is that we are trying to find the value of these integrals between 1 and . An integral with a limit of infinity is called an improper integral and we can't evaluate it simply by plugging the value infinity into the normal equation for a definite integral. Instead, we must first calculate the definite integral up to some finite limit b and then calculate the limit of the result as b tends to :
Volume
We can calculate the horn's volume using the volume integral above, so
The total volume of this infinitely long trumpet isπ.
Surface Area
To determine the surface area, we first need the function’s derivative:
Now plug it into the surface area formula and we have:
This is an improper integral and it's hard to evaluate, but since in our interval
So, we have :
Now,we evaluate this last integral
So the surface are is infinite.
% Define the function for Gabriel's Horn
gabriels_horn = @(x) 1 ./ x;
% Create a range of x values
x = linspace(1, 40, 4000); % Increase the number of points for better accuracy
y = gabriels_horn(x);
% Create the meshgrid
theta = linspace(0, 2 * pi, 6000); % Increase theta points for a smoother surface
[X, T] = meshgrid(x, theta);
Y = gabriels_horn(X) .* cos(T);
Z = gabriels_horn(X) .* sin(T);
% Plot the surface of Gabriel's Horn
figure('Position', [200, 100, 1200, 900]);
surf(X, Y, Z, 'EdgeColor', 'none', 'FaceAlpha', 0.9);
hold on;
% Plot the central axis
plot3(x, zeros(size(x)), zeros(size(x)), 'r', 'LineWidth', 2);
% Set labels
xlabel('x');
ylabel('y');
zlabel('z');
% Adjust colormap and axis properties
colormap('gray');
shading interp; % Smooth shading
% Adjust the view
view(3);
axis tight;
grid on;
% Add formulas as text annotations
dim1 = [0.4 0.7 0.3 0.2];
annotation('textbox',dim1,'String',{'$$V = \pi \int_{1}^{a} \left( \frac{1}{x} \right)^2 dx = \pi \left( 1 - \frac{1}{a} \right)$$', ...
'', ... % Add an empty line for larger gap
'$$\lim_{a \to \infty} V = \lim_{a \to \infty} \pi \left( 1 - \frac{1}{a} \right) = \pi$$'}, ...
'Interpreter','latex','FontSize',12, 'EdgeColor','none', 'FitBoxToText', 'on');
dim2 = [0.4 0.5 0.3 0.2];
annotation('textbox',dim2,'String',{'$$A = 2\pi \int_{1}^{a} \frac{1}{x} \sqrt{1 + \left( -\frac{1}{x^2} \right)^2} dx > 2\pi \int_{1}^{a} \frac{dx}{x} = 2\pi \ln(a)$$', ...
'', ... % Add an empty line for larger gap
'$$\lim_{a \to \infty} A \geq \lim_{a \to \infty} 2\pi \ln(a) = \infty$$'}, ...
'Interpreter','latex','FontSize',12, 'EdgeColor','none', 'FitBoxToText', 'on');
% Add Gabriel's Horn label
dim3 = [0.3 0.9 0.3 0.1];
annotation('textbox',dim3,'String','Gabriel''s Horn', ...
'Interpreter','latex','FontSize',14, 'EdgeColor','none', 'HorizontalAlignment', 'center');
hold off
daspect([3.5 1 1]) % daspect([x y z])
view(-27, 15)
lightangle(-50,0)
lighting('gouraud')
The properties of this figure were first studied by Italian physicist and mathematician Evangelista Torricelli in the 17th century.
Acknowledgment
I would like to express my sincere gratitude to all those who have supported and inspired me throughout this project.
First and foremost, I would like to thank the mathematician and my esteemed colleague, Stavros Tsalapatis, for inspiring me with the fascinating subject of Gabriel's Horn.
I am also deeply thankful to Mr. @Star Strider for his invaluable assistance in completing the final code.
References:
  1. How to Find the Volume and Surface Area of Gabriel's Horn
  2. Gabriel's Horn
  3. An Understanding of a Solid with Finite Volume and Infinite Surface Area.
  4. IMPROPER INTEGRALS: GABRIEL’S HORN
  5. Gabriel’s Horn and the Painter's Paradox in Perspective
Marisa
Marisa
Posted 2024년 7월 22일 0:44

I am trying to earn my Intro to MATLAB badge in Cody, but I cannot click the Roll the Dice! problem. It simply is not letting me click it, therefore I cannot earn my badge. Does anyone know who I should contact or what to do?
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)
To provide talking points, here's a YouTube video I recorded.
Things to observe:
  1. 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.
  2. 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:
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:
Or maybe use the middle-mouse button to temporarily use this mode (a mouse setting in, e.g., Abaqus/CAE).
Honzik
Honzik
Posted 2024년 7월 9일 22:11

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?
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.
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
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.
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.
An option for 10th degree polynomials but no weighted linear least squares. Seriously? Jesse
What do you think about the NVIDIA's achivement of becoming the top giant of manufacturing chips, especially for AI world?
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.
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!

Interesting Questions

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!
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.

Popular Discussions

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.
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.

From the Blogs

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.
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.
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!
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
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
% Calculate R0
R0 = beta / gamma
R0 = 0.9000
% Initial state values
initial_state_values = [1000000; 1; 0; 0]; % S, I, R, cum_inc
% 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];
% 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';
while t < tf
rates = a(state);
rate_sum = sum(rates);
if rate_sum == 0
break;
end
tau = -log(rand) / rate_sum;
t = t + tau;
r = rand * rate_sum;
cum_sum_rates = cumsum(rates);
reaction_index = find(cum_sum_rates >= r, 1);
state = state + nu(:, reaction_index);
% Update cumulative incidence if infection occurred
if reaction_index == 1
state(4) = state(4) + 1; % Increment cumulative incidence
end
t_values = [t_values; t];
state_values = [state_values; state'];
end
end
% 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];
% Set random seed for reproducibility
rng(11);
% Initialize plot
figure;
hold on;
for i = 1:n_sims
[t, output] = gillespie_ssa(initial_state_values, a, nu, tf);
% 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
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
xlabel('Time (days)');
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
title(['Stochastic model output for R0 = ', num2str(R0)]);
subtitle([num2str(n_sims), ' simulations']);
xlim([0 tf]);
grid on;
hold off;
end
% Simulate the model 100 times and plot cumulative incidence
simulate_stoch_model(beta, gamma, n_sims, tf, initial_state_values, R0, 'cumulative_incidence');
% Simulate the model 100 times and plot prevalence
simulate_stoch_model(beta, gamma, n_sims, tf, initial_state_values, R0, 'prevalence');
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.
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.
goc3
goc3
Posted 2024년 6월 13일

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.
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.
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.
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, []);