/matlabcentral/discussions/channels
Channels Discussions
2024-03-01T13:50:12Z
tag:au.mathworks.com,2005:Topic/844101
2024-02-02T17:41:51Z
2024-02-04T11:24:23Z
Read this before posting
<p>Hello and a warm welcome to all! We're thrilled to have you visit our community. MATLAB Central is a place for learning, sharing, and connecting with others who share your passion for MATLAB and Simulink. To ensure you have the best experience, here are some tips to get you started:
Read the Community Guidelines: Understanding our community standards is crucial. Please take a moment to familiarize yourself with them. Keep in mind that posts not adhering to these guidelines may be flagged by moderators or other community members.
Ask Technical Questions at MATLAB Answers: If you have questions related to MathWorks products, head over to MATLAB Answers (new question form - Ask the community). It's the go-to spot for technical inquiries, with responses often provided within an hour, depending on the complexity of the question and volunteer availability. To increase your chances of a speedy reply, check out our tips on how to craft a good question (link to post on asking good questions).
Choosing the Right Channel: We offer a variety of discussion channels tailored to different contexts. Select the one that best fits your post. If you're unsure, the General channel is always a safe bet. If you feel there's a need for a new channel, we encourage you to suggest it in the Ideas channel.
Reporting Issues: If you encounter posts that violate our guidelines, please use the π©Flag/Report feature (found in the 3-dot menu) to bring them to our attention.
Quality Control: We strive to maintain a high standard of discussion. Accounts that post spam or too much nonsense may be subject to moderation, which can include temporary suspensions or permanent bans.
Share Your Ideas: Your feedback is invaluable. If you have suggestions on how we can improve the community or MathWorks products, the Ideas channel is the perfect place to voice your thoughts.
Enjoy yourself and have fun! We're committed to fostering a supportive and educational environment. Dive into discussions, share your expertise, and grow your knowledge. We're excited to see what you'll contribute to the community!</p>
David
https://au.mathworks.com/matlabcentral/profile/authors/4480925
tag:au.mathworks.com,2005:Topic/837514
2023-12-04T19:29:04Z
2024-03-01T09:09:04Z
New Community Feature: AI Chat Playground
<p>The MATLAB AI Chat Playground is now open to the whole community! Answer questions, write first draft MATLAB code, and generate examples of common functions with natural language.
The playground features a chat panel next to a lightweight MATLAB code editor. Use the chat panel to enter natural language prompts to return explanations and code. You can keep chatting with the AI to refine the results or make changes to the output.</p><p>Give it a try, provide feedback on the output, and check back often as we make improvements to the model and overall experience.</p>
Hans Scharler
https://au.mathworks.com/matlabcentral/profile/authors/5863695
tag:au.mathworks.com,2005:Topic/831462
2023-11-07T18:43:52Z
2023-11-09T13:55:07Z
π The MATLAB AI Chat Playground Has Launched
<p>The MATLAB AI Chat Playground is open to everyone!
Check it out here on the community: https://www.mathworks.com/matlabcentral/playground</p><p>I just published a blog post announcing the release.</p>
Hans Scharler
https://au.mathworks.com/matlabcentral/profile/authors/5863695
tag:au.mathworks.com,2005:Topic/847476
2024-02-29T21:59:02Z
2024-03-01T13:50:12Z
How to Draw a Happy Sheep in MATLAB!
<p>Let us consider how to draw a Happy Sheep. A Happy Sheep was introduced in the MATLAB Mini Hack contest: Happy Sheep!
In this contest there was the strict limitation on the code length. So the code of the Happy Sheep is very compact and is only 280 characters long. We will analyze the process of drawing the Happy Sheep in MATLAB step by step. The explanations of the even more compact version of the code of the same sheep are given below.
So, how to draw a sheep? It is very easy. We could notice that usually a sheep is covered by crimped wool. Therefore, a sheep could be painted using several geometrical curves of similar types. Of course, then it will be an abstract model of the real sheep. Let us select two mathematical curves, which are the most appropriate for our goal. They are an ellipse for smooth parts of the sheep and an ellipse combined with a rose for woolen parts of the sheep.
Let us recall the mathematical formulas of these curves. A parametric representation of the standard ellipse is the following:</p><p>Also we will use the following parametric representation of the rose (rhodonea) curve:</p><p>This curve was named by the mathematician Guido Grandi.
Let us combine them in one curve and add possible shifts:</p><p>Now if we would like to create an ellipse, we will set and . If we would like to create a rose, we will set and . If we would like to shift our curve, we will set and to the required values. Of course, we could set all non-zero parameters to combine both chosen curves and use the shifts.
Let us describe how to create these curves using the MATLAB code. To make the code more compact, it is possible to program both formulas for the combined curve in one line using the anonymous function. We could make the code more compact using the function handles for sine and cosine functions. Then the MATLAB code for an example of the ellipse curve will be the following.
% Handles
s=@sin;
c=@cos;
% Ellipse + Polar Rose
F=@(t,a,f) a(1)*f(t)+s(a(2)*t).*f(t)+a(3);
% Angles
t=0:.1:7;
% Parameters
E = [5 7;0 0;0 0];
% Painting
figure;
plot(F(t,E(:,1),c),F(t,E(:,2),s),'LineWidth',10);
axis equal
The parameter varies from 0 to 7, which is the nearest integer greater than , with the step 0.1. The result of this code is the following ellipse curve with and .</p><p>This ellipse is described by the following parametric equations:</p><p>The MATLAB code for an example of the rose curve will be the following.
% Handles
s=@sin;
c=@cos;
% Ellipse + Polar Rose
F=@(t,a,f) a(1)*f(t)+s(a(2)*t).*f(t)+a(3);
% Angles
t=0:.1:7;
% Parameters
R = [0 0;4 4;0 0];
% Painting
figure;
plot(F(t,R(:,1),c),F(t,R(:,2),s),'LineWidth',10);
axis equal
The result of this code is the following rose curve with and .</p><p>This rose is described by the following parametric equations:</p><p>Obviously, now we are ready to draw main parts of our sheep! As we reproduce an abstract model of the sheep, let us select the following main parts for the representation: head, eyes, hoofs, body, crown, and tail. We will use ellipses for the first three parts in this list and ellipses combined with roses for the last three ones.
First let us describe drawing of each part independently.
The following MATLAB code will be used to do this.
% Handles
s=@sin;
c=@cos;
% Ellipse + Polar Rose
F=@(t,a,f) a(1)*f(t)+s(a(2)*t).*f(t)+a(3);
% Angles
t=0:.1:7;
% Parameters
Head = 1;
Eyes = 2:3;
Hoofs = 4:7;
Body = 8;
Crown = 9;
Tail = 10;
G=-13;
P=[5 7 repmat([.1 .5],1,6) 6 4 14 9 3 3;zeros(1,14) 8 8 12 12 4 4;...
-15 2 G 3 -17 3 -3 G 0 G 9 G 12 G -15 12 4 3 20 7];</p><p>% Painting
figure;
hold;
for i=Head
plot(F(t,P(:,2*i-1),c),F(t,P(:,2*i),s),'LineWidth',10);
end
axis([-25 25 -15 20]);</p><p>figure;
hold;
for i=Eyes
plot(F(t,P(:,2*i-1),c),F(t,P(:,2*i),s),'LineWidth',10);
end
axis([-25 25 -15 20]);</p><p>figure;
hold;
for i=Hoofs
plot(F(t,P(:,2*i-1),c),F(t,P(:,2*i),s),'LineWidth',10);
end
axis([-25 25 -15 20]);</p><p>figure;
hold;
for i=Body
plot(F(t,P(:,2*i-1),c),F(t,P(:,2*i),s),'LineWidth',10);
end
axis([-25 25 -15 20]);</p><p>figure;
hold;
for i=Crown
plot(F(t,P(:,2*i-1),c),F(t,P(:,2*i),s),'LineWidth',10);
end
axis([-25 25 -15 20]);</p><p>figure;
hold;
for i=Tail
plot(F(t,P(:,2*i-1),c),F(t,P(:,2*i),s),'LineWidth',10);
end
axis([-25 25 -15 20]);
The parameters , , , , , and are written in the different submatrices of the matrix . The code generates the following curves to illustrate the different parts of our sheep.
The following ellipse describes the head of the sheep.</p><p>The following submatrix of the matrix represents its parameters.</p><p>The parametric equations of the head are the following:</p><p>The following ellipses describe the eyes of the sheep.</p><p>The following submatrices of the matrix represent their parameters.</p><p>The parametric equations of the left and right eyes correspondingly are the following:</p><p>The following ellipses describe the hoofs of the sheep.</p><p>The following submatrices of the matrix represent their parameters.</p><p>The parametric equations of the right front, left front, right hind, and left hind hoofs correspondingly are the following:</p><p>The following ellipse combined with the rose describes the crown of the sheep.</p><p>The following submatrix of the matrix represents its parameters.</p><p>The parametric equations of the crown are the following:</p><p>The following ellipse combined with the rose describes the body of the sheep.</p><p>The following submatrix of the matrix represents its parameters.</p><p>The parametric equations of the body are the following:</p><p>The following ellipse combined with the rose describes the tail of the sheep.</p><p>The following submatrix of the matrix represents its parameters.</p><p>The parametric equations of the tail are the following:</p><p>Now all the parts of our sheep should be put together! It is very easy because all the parts are described by the same equations with different parameters.
The following code helps us to accomplish this goal and ultimately draw a Happy Sheep in MATLAB!
% Happy Sheep!
% By Victoria A. Sablina
% Handles
s=@sin;
c=@cos;
% Ellipse + Rose
F=@(t,a,f) a(1)*f(t)+s(a(2)*t).*f(t)+a(3);
% Angles
t=0:.1:7;
% Parameters
% Head (1:2)
% Eyes (3:6)
% Hoofs (7:14)
% Crown (15:16)
% Body (17:18)
% Tail (19:20)
G=-13;
P=[5 7 repmat([.1 .5],1,6) 6 4 14 9 3 3;zeros(1,14) 8 8 12 12 4 4;...
-15 2 G 3 -17 3 -3 G 0 G 9 G 12 G -15 12 4 3 20 7];
% Painting
hold;
for i=1:10
plot(F(t,P(:,2*i-1),c),F(t,P(:,2*i),s),'LineWidth',10);
end
This code is even more compact than the original code from the contest. It is only 253 instead of 280 characters long and generates the same Happy Sheep!</p><p>Our sheep is happy, because of becoming famous in the MATLAB community, a star!
Congratulations! Now you know how to draw a Happy Sheep in MATLAB!
Thank you for reading!</p>
Victoria
https://au.mathworks.com/matlabcentral/profile/authors/1777777
tag:au.mathworks.com,2005:Topic/847426
2024-02-29T14:34:15Z
2024-02-29T18:16:28Z
Enhancing GitHub and File Exchange connection: MATLAB and Simulink Integration for GitHub Unveiled
<p>The File Exchange team is thrilled to introduce a more streamlined approach to working with GitHub and File Exchange - the MATLAB and Simulink Integration for GitHub!
Key Enhancements:
- Improves the existing connection between File Exchange and GitHub, ensuring quicker reflection of changes made in GitHub within File Exchange.
- Aligns with GitHub's standard and supported approach to building integrations.</p><p>Action Required for File Exchange Contributors!
If you are a File Exchange contributor and have linked any submissions to GitHub, it is essential to install the App.</p><p>Starting April 16, 2024, your File Exchange submissions will no longer update automatically unless you take the following steps:
1. Visit your My File Exchange page.
2. Follow the prompts on the page to install MATLAB and Simulink Integration for GitHub.</p><p>3. Complete the necessary steps in GitHub.
4. Return to the My File Exchange page and verify the installation.</p><p>A detailed description of the process is available here.</p><p>If you prefer your File Exchange submission not to update automatically from GitHub, no action is required. Users will still be able to find and download your submissions. However, to release a new version of your code, you must either install the GitHub App or disconnect from GitHub and manually upload new versions of your code.</p><p>Should you have any questions or encounter issues with the App, please feel free to comment on this post!</p>
Chen Lin
https://au.mathworks.com/matlabcentral/profile/authors/6682740
tag:au.mathworks.com,2005:Topic/847321
2024-02-28T20:25:39Z
2024-02-29T00:49:24Z
Set colormap limits when creating m colors
<p>Several of the colormaps are great for a 256 color surface plot, but aren't well optimized for extracting m colors for plotting several independent lines. The issue is that many colormaps have start/end colors that are too similar or are suboptimal colors for lines. There are certainly many workarounds for this, but it would be a great quality of life to adjust that directly when calling this.
Example:
x = linspace(0,2*pi,101)';
y = [1:6].*cos(x);
figure; plot(x,y,'LineWidth',2); grid on; axis tight;
And now if I wanted to color these lines, I could use something like turbo(6) or gray(6) and then apply it using colororder.
colororder(turbo(6))
But my issue is that the ends of the colormap are too similar. For other colormaps, you may get lines that are too light to be visible against the white background. There are plenty of workarounds, with my preference being to create extra colors and truncate that before using colororder.
cmap = turbo(8); cmap = cmap(2:end-1,:); % Truncate the end colors
figure; plot(x,y,'LineWidth',2); grid on; axis tight;
colororder(cmap)
I think it would be really awesome to add some name-argument input pair to these colormaps that can specify the range you want so this could even be done inside the colororder calling if desired. An example of my proposed solution would look something like this:
cmap = turbo(6,'Range',[0.1 0.8]); % Proposed idea to add functionality
Where in this scenario, the resulting colormap would be 6 equally spaced colors that range from 10% to 80% of the total color range. This would be especially nice because you could more quickly modify the range of colors, or you could set the limits regardless of whether you need to plot 3, 6, or 20 lines.</p>
Emma Farnan
https://au.mathworks.com/matlabcentral/profile/authors/4779029
tag:au.mathworks.com,2005:Topic/847171
2024-02-27T14:55:31Z
2024-02-29T05:25:16Z
How to access English-speaking forum?
<p>I asked my question in the general forum and a few minutes later it was deleted. Perhaps this is a better place?
Rather than using my German regional forum (as I do not speak German), I want to ask questions in an international English-speaking forum. Presumably there should be an international English forum for everyone around the world, as English is the first or second language of everyone who has gone to school. Where is it?</p>
Nikolaos
https://au.mathworks.com/matlabcentral/profile/authors/32932841
tag:au.mathworks.com,2005:Topic/847073
2024-02-26T21:58:47Z
2024-02-28T19:32:21Z
Celebrating @VBBV: Our Newest Member of the Editors' Club
<p>Big congratulations to @VBBV for achieving the remarkable milestone of 3,000 reputation points, earning the prestigious title of Editor within our community.
This achievement is a testament to @VBBV's exceptional contributions and steadfast commitment to the community. These efforts have also been endorsed by fellow top contributors, underscoring the value and impact of @VBBV's expertise.</p><p>Welcome to the Editors' Club, @VBBV β we are excited to witness and support your continued journey and influence within our community!</p>
Chen Lin
https://au.mathworks.com/matlabcentral/profile/authors/6682740
tag:au.mathworks.com,2005:Topic/846973
2024-02-26T14:19:12Z
2024-02-29T07:42:20Z
Which of the following will not produce a 3x3 array of zeros in MATLAB?
goc3
https://au.mathworks.com/matlabcentral/profile/authors/5349647
tag:au.mathworks.com,2005:Topic/846688
2024-02-23T13:24:21Z
2024-02-28T14:03:23Z
MATLAB O/X QUIZ
<p>MATLAB O/X Quiz
Answer BEFORE Googling!</p><p>An infinite loop can be made using "for".
"A == A" is always true.
"round(2.5)" is 3.
"round(-0.5)" is 0.</p>
lazymatlab
https://au.mathworks.com/matlabcentral/profile/authors/12626206
tag:au.mathworks.com,2005:Topic/846633
2024-02-22T13:47:56Z
2024-02-22T13:47:56Z
New Quantum Computing Cheat Sheet!
<p>MATLAB Support Package for Quantum Computing lets you build, simulate, and run quantum algorithms.
Check out the Cheat Sheet here!</p>
Ben Pasquariello
https://au.mathworks.com/matlabcentral/profile/authors/10224191
tag:au.mathworks.com,2005:Topic/846083
2024-02-17T08:38:13Z
2024-02-20T16:19:41Z
νλ ¬μμ λ©΄μ μ΄λ€? Determinant is area?
<p>2 x 2 νλ ¬μ νλ ¬μμ
νλ ¬μ λ row λ²‘ν°λ‘ μ μλλ ννμ¬λ³νμ λ©΄μ μ
λλ€.
λ¬Όλ‘ λ column λ²‘ν°λ‘ μ μλλ ννμ¬λ³νμ λ©΄μ μ΄κΈ°λ ν©λλ€.
μ’ λ μ ννλ signed areaμ
λλ€. λ©΄μ μ΄ μμκ° λ μλ μλ€λ λ»μ΄μ£ .
νλ ¬μ λ ν(λλ λ μ΄)μ λ§λ°κΎΈλ©΄ νλ ¬μμ λΆνΈλ λ°λκ³ λ©΄μ μ λΆνΈλ λ°λμ΄μΌν©λλ€.</p><p>μΌλ°μ μΌλ‘ n x n νλ ¬μ νλ ¬μμ
κ° row λ²‘ν°(λλ κ° column λ²‘ν°)λ‘ μ μλλ Nμ°¨μ κ³΅κ°μ ννλ©΄μ²΄(?)μ signed areaμ
λλ€.
μ λλ‘ μ΄ν΄νλ €λ©΄ λμνμ κ°λ
μ λ§μ΄ κ°μ§κ³ μμΌ νλλ° μμΈν μ€λͺ
μ μλ΅ν©λλ€.(=μ λ λͺ¨λ₯Έλ€λ λ»)
λ μμΈν μκ³ μΆμΌμλ©΄ μννλ λ§νμ 'λμ΄ μ΄μΌκΈ°' νΈμ μΆμ²ν©λλ€.
μνμ μΈ μ μλ₯Ό μκ³ μΆμΌμλ©΄ μν€νΌλμλ₯Ό λ³΄μλ©΄ λ©λλ€.</p><p>μ΄λ κ² μκ²Όμ΅λλ€. μ’ λ¬΄μμ΅λλ€.</p><p>μλ μ½λλ...
2 x 2 νλ ¬μ λν΄μ μ΄κ²μ μμ μμ΄ κ·Έλ¦Όλ§μΌλ‘ μ¦λͺ
νλ κ³Όμ μ
λλ€.
gif μμ±μλ ScreenToGifλ₯Ό μ¬μ©νμ΅λλ€. (gif λ§λ€κΈ°μ μ΄κ² νΉμμ§±μΈλ―)</p><p>Determinant of 2 x 2 matrix is...
An area of a parallelogram defined by two row vectors.
Of course, same one defined by two column vectors.
Precisely, a signed area, which means area can be negative.
If two rows (or columns) are swapped, both the sign of determinant and area change.</p><p>More generally, determinant of n x n matrix is...
Signed area of parallelepiped defined by rows (or columns) of the matrix in n-dim space.
For a full understanding, a lot of concepts from abstract algebra should be brought, which I will not write here. (Cuz I don't know them.)
For a mathematical definition of determinant, visit wikipedia.</p><p>A little scary, isn't it?</p><p>The code below is...
A process to prove the equality of the determinant of 2 x 2 matrix and the area of parallelogram.
ScreenToGif is used to generate gif animation (which is, to me, the easiest way to make gif).</p><p>% λ μ (a, b), (c, d)μ μ’ν
a = 4;
b = 1;
c = 1;
d = 3;</p><p>% patch μ pre-define
lightgreen = [144, 238, 144]/255;
lightblue = [169, 190, 228]/255;
lightorange = [247, 195, 160]/255;</p><p>% animation params.
anim_Nsteps = 30;</p><p>% create window
figure('WindowStyle','docked')
ax = axes;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
ax.XTick = [];
ax.YTick = [];</p><p>hold on
ax.XLim = [-.4, a+c+1];
ax.YLim = [-.4, b+d+1];</p><p>% create ad-bc patch
area = patch([0, a, a+c, c], [0, b, b+d, d], lightgreen);
p_ab = plot(a, b, 'ko', 'MarkerFaceColor', 'k');
p_cd = plot(c, d, 'ko', 'MarkerFaceColor', 'k');
p_ab.UserData = text(a+0.1, b, '(a, b)', 'FontSize',16);
p_cd.UserData = text(c+0.1, d-0.2, '(c, d)', 'FontSize',16);
area.UserData = text((a+c)/2-0.5, (b+d)/2, 'ad-bc', 'FontSize', 18);</p><p>pause</p><p>%% Is this really ad-bc?</p><p>area.UserData.String = 'ad-bc...?';</p><p>pause</p><p>%% fade out ad-bc</p><p>fadeinout(area, 0)
area.UserData.Visible = 'off';</p><p>pause</p><p>%% fade in ad block</p><p>rect_ad = patch([0, a, a, 0], [0, 0, d, d], lightblue, 'EdgeAlpha', 0, 'FaceAlpha', 0);
uistack(rect_ad, 'bottom');</p><p>fadeinout(rect_ad, 1, t_pause=0.003)
draw_gridline(rect_ad, ["23", "34"])
rect_ad.UserData = text(mean(rect_ad.XData), mean(rect_ad.YData), 'ad', 'FontSize', 20, 'HorizontalAlignment', 'center');</p><p>pause</p><p>%% fade-in bc block</p><p>rect_bc = patch([0, c, c, 0], [0, 0, b, b], lightorange, 'EdgeAlpha', 0, 'FaceAlpha', 0);</p><p>fadeinout(rect_bc, 1, t_pause=0.0035)
draw_gridline(rect_bc, ["23", "34"])
rect_bc.UserData = text(b/2, c/2, 'bc', 'FontSize', 20, 'HorizontalAlignment', 'center');</p><p>pause</p><p>%% slide ad block</p><p>patch_slide(rect_ad, ...
[0, 0, 0, 0], [0, b, b, 0], t_pause=0.004)</p><p>draw_gridline(rect_ad, ["12", "34"])</p><p>pause</p><p>%% slide ad block</p><p>patch_slide(rect_ad, ...
[0, 0, d/(d/c-b/a), d/(d/c-b/a)],...
[0, 0, b/a*d/(d/c-b/a), b/a*d/(d/c-b/a)], t_pause=0.004)</p><p>draw_gridline(rect_ad, ["14", "23"])</p><p>pause</p><p>%% slide bc block</p><p>uistack(p_cd, 'top')
patch_slide(rect_bc, ...
[0, 0, 0, 0], [d, d, d, d], t_pause=0.004)</p><p>draw_gridline(rect_bc, "34")
pause</p><p>%% slide bc block</p><p>patch_slide(rect_bc, ...
[0, 0, a, a], [0, 0, 0, 0], t_pause=0.004)</p><p>draw_gridline(rect_bc, "23")</p><p>pause</p><p>%% slide bc block</p><p>patch_slide(rect_bc, ...
[d/(d/c-b/a), 0, 0, d/(d/c-b/a)], ...
[b/a*d/(d/c-b/a), 0, 0, b/a*d/(d/c-b/a)], t_pause=0.004)</p><p>pause</p><p>%% finalize: fade out ad, bc, and fade in ad-bc</p><p>rect_ad.UserData.Visible = 'off';
rect_bc.UserData.Visible = 'off';</p><p>fadeinout([rect_ad, rect_bc, area], [0, 0, 1])</p><p>area.UserData.String = 'ad-bc';
area.UserData.Visible = 'on';</p><p>%% functions</p><p>function fadeinout(objs, inout, options)
arguments
objs
inout % 1μ΄λ©΄ fade-in, 0μ΄λ©΄ fade-out
options.anim_Nsteps = 30
options.t_pause = 0.003
end</p><p>for alpha = linspace(0, 1, options.anim_Nsteps)
for i = 1:length(objs)
switch objs(i).Type
case 'patch'
objs(i).FaceAlpha = (inout(i)==1)*alpha + (inout(i)==0)*(1-alpha);
objs(i).EdgeAlpha = (inout(i)==1)*alpha + (inout(i)==0)*(1-alpha);
case 'constantline'
objs(i).Alpha = (inout(i)==1)*alpha + (inout(i)==0)*(1-alpha);
end
pause(options.t_pause)
end
end</p><p>end</p><p>function patch_slide(obj, x_dist, y_dist, options)
arguments
obj
x_dist
y_dist
options.anim_Nsteps = 30
options.t_pause = 0.003
end</p><p>dx = x_dist/options.anim_Nsteps;
dy = y_dist/options.anim_Nsteps;
for i=1:options.anim_Nsteps
obj.XData = obj.XData + dx(:);
obj.YData = obj.YData + dy(:);
obj.UserData.Position(1) = mean(obj.XData);
obj.UserData.Position(2) = mean(obj.YData);
pause(options.t_pause)
end</p><p>end</p><p>function draw_gridline(patch, where)</p><p>ax = patch.Parent;
for i=1:length(where)
v1 = str2double(where{i}(1));
v2 = str2double(where{i}(2));
x1 = patch.XData(v1);
x2 = patch.XData(v2);
y1 = patch.YData(v1);
y2 = patch.YData(v2);
if x1==x2
xline(x1, 'k--')
else
fplot(@(x) (y2-y1)/(x2-x1)*(x-x1)+y1, [ax.XLim(1), ax.XLim(2)], 'k--')
end
end</p><p>end</p>
lazymatlab
https://au.mathworks.com/matlabcentral/profile/authors/12626206
tag:au.mathworks.com,2005:Topic/846048
2024-02-16T12:47:36Z
2024-02-16T14:30:14Z
Render landscapes
<p>I think that MATLAB's Flipbook Mini Hack had quite some inspiring entries. My work largely deals with digital elevation models (DEMs). Hence I really liked the random renderings of landscapes, in particular this one written by Tim which inspired me to adopt the code and apply to the example data that comes with my software TopoToolbox. The results and code are shown here.</p>
Wolfgang Schwanghart
https://au.mathworks.com/matlabcentral/profile/authors/870595
tag:au.mathworks.com,2005:Topic/846038
2024-02-16T12:07:48Z
2024-02-16T16:57:52Z
Producing animated gifs from MATLAB Flipbook Mini Hack entries
<p>On Valentine's day, the MathWorks linkedIn channel posted this animated gif</p><p>and immeditaely everyone wanted the code! It turns out that this is the result of my remix of @Zhaoxu Liu / slandarer's entry on the MATLAB Flipbook Mini Hack.
I pointed people to the Flipbook entry but, of course, that just gave the code to render a single frame and people wanted the full code to render the animated gif. That way, they could make personalised versions
I just published a blog post that gives the code used by the team behind the Mini Hack to produce the animated .gifs https://blogs.mathworks.com/matlab/2024/02/16/producing-animated-gifs-from-matlab-flipbook-mini-hack-entries/
Thanks again to @Zhaoxu Liu / slandarer for a great entry that seems like it will live for a long time :)</p>
Mike Croucher
https://au.mathworks.com/matlabcentral/profile/authors/20789457
tag:au.mathworks.com,2005:Topic/845998
2024-02-15T23:19:26Z
2024-02-20T15:57:52Z
Tricks for Sphere Texturing
<p>If you've dabbled in "procedural generation," (algorithmically generating natural features), you may have come across the problem of sphere texturing. How to seamlessly texture a sphere is not immediately obvious. Watch what happens, for example, if you try adding power law noise to an evenly sampled grid of spherical angle coordinates (i.e. a "UV sphere" in Blender-speak):
% Example: how [not] to texture a sphere:
rng(2, 'twister'); % Make what I have here repeatable for you</p><p>% Make our radial noise, mapped onto an equal spaced longitude and latitude
% grid.
N = 51;
b = linspace(-1, 1, N).^2;
r = abs(ifft2(exp(6i*rand(N))./(b'+b+1e-5))); % Power law noise
r = rescale(r, 0, 1) + 5;
[lon, lat] = meshgrid(linspace(0, 2*pi, N), linspace(-pi/2, pi/2, N));
[x2, y2, z2] = sph2cart(lon, lat, r);
r2d = @(x)x*180/pi;</p><p>% Radial surface texture
subplot(1, 3, 1);
imagesc(r, 'Xdata', r2d(lon(1,:)), 'Ydata', r2d(lat(:, 1)));
xlabel('Longitude (Deg)');
ylabel('Latitude (Deg)');
title('Texture (radial variation)');</p><p>% View from z axis
subplot(1, 3, 2);
surf(x2, y2, z2, r);
axis equal
view([0, 90]);
title('Top view');</p><p>% Side view
subplot(1, 3, 3);
surf(x2, y2, z2, r);
axis equal
view([-90, 0]);
title('Side view');</p><p>The created surface shows "pinching" at the poles due to different radial values mapping to the same location. Furthermore, the noise statistics change based on the density of the sampling on the surface.
How can this be avoided? One standard method is to create a textured volume and sample the volume at points on a sphere. Code for doing this is quite simple:
rng default % Make our noise realization repeatable</p><p>% Create our 3D power-law noise
N = 201;
b = linspace(-1, 1, N);
[x3, y3, z3] = meshgrid(b, b, b);
b3 = x3.^2 + y3.^2 + z3.^2;
r = abs(ifftn(ifftshift(exp(6i*randn(size(b3)))./(b3.^1.2 + 1e-6))));</p><p>% Modify it - make it more interesting
r = rescale(r);
r = r./(abs(r - 0.5) + .1);</p><p>% Sample on a sphere
[x, y, z] = sphere(500);</p><p>% Plot
ir = interp3(x3, y3, z3, r, x, y, z, 'linear', 0);
surf(x, y, z, ir);
shading flat
axis equal off
set(gcf, 'color', 'k');
colormap(gray);
The result of evaluating this code is a seamless, textured sphere with no discontinuities at the poles or variation in the spatial statistics of the noise texture:</p><p>But what if you want to smooth it or perform some other local texture modification? Smoothing the volume and resampling is not equivalent to smoothing the surficial features shown on the map above.
A more flexible alternative is to treat the samples on the sphere surface as a set of interconnected nodes that are influenced by adjacent values. Using this approach we can start by defining the set of nodes on a sphere surface. These can be sampled almost arbitrarily, though the noise statistics will vary depending on the sampling strategy.
One noise realisation I find attractive can be had by randomly sampling a sphere. Normalizing a point in N-dimensional space by its 2-norm projects it to the surface of an N-dimensional unit sphere, so randomly sampling a sphere can be done very easily using randn() and vecnorm():
N = 5e3; % Number of nodes on our sphere
g=randn(3,N); % Random 3D points around origin
p=g./vecnorm(g); % Projected to unit sphere
The next step is to find each point's "neighbors." The first step is to find the convex hull. Since each point is on the sphere, the convex hull will include each point as a vertex in the triangulation:
k=convhull(p');
In the above, k is an N x 3 set of indices where each row represents a unique triangle formed by a triplicate of points on the sphere surface. The vertices of the full set of triangles containing a point describe the list of neighbors to that point.
What we want now is a large, sparse symmetric matrix where the indices of the columns & rows represent the indices of the points on the sphere and the nth row (and/or column) contains non-zero entries at the indices corresponding to the neighbors of the nth point.
How to do this? You could set up a tiresome nested for-loop searching for all rows (triangles) in k that contain some index n, or you could directly index via:
c=@(x)sparse(k(:,x)*[1,1,1],k,1,N,N);
t=c(1)|c(2)|c(3);
The result is the desired sparse connectivity matrix: a matrix with non-zero entries defining neighboring points.
So how do we create a textured sphere with this connectivity matrix? We will use it to form a set of equations that, when combined with the concept of "regularization," will allow us to determine the properties of the randomness on the surface. Our regularizer will penalize the difference of the radial distance of a point and the average of its neighbors. To do this we replace the main diagonal with the negative of the sum of the off-diagonal components so that the rows and columns are zero-mean. This can be done via:
w=spdiags(-sum(t,2)+1,0,double(t));
Now we invoke a bit of linear algebra. Pretend x is an N-length vector representing the radial distance of each point on our sphere with the noise realization we desire. Y will be an N-length vector of "observations" we are going to generate randomly, in this case using a uniform distribution (because it has a bias and we want a non-zero average radius, but you can play around with different distributions than uniform to get different effects):
Y=rand(N,1);
and A is going to be our "transformation" matrix mapping x to our noisy observations:
Ax = Y
In this case both x and Y are N length vectors and A is just the identity matrix:
A = speye(N);
Y, however, doesn't create the noise realization we want. So in the equation above, when solving for x we are going to introduce a regularizer which is going to penalize unwanted behavior of x by some amount. That behavior is defined by the point-neighbor radial differences represented in matrix w. Our estimate of x can then be found using one of my favorite Matlab assets, the "\" operator:
smoothness = 10; % Smoothness penalty: higher is smoother
x = (A+smoothness*w'*w)\Y; % Solving for radii
The vector x now contains the radii with the specified noise realization for the sphere which can be created simply by multiplying x by p and plotting using trisurf:
p2 = p.*x';
trisurf(k,p2(1,:),p2(2,:),p2(3,:),'FaceC', 'w', 'EdgeC', 'none','AmbientS',0,'DiffuseS',0.6,'SpecularS',1);
light;
set(gca, 'color', 'k');
axis equal</p><p>The following images show what happens as you change the smoothness parameter using values [.1, 1, 10, 100] (left to right):</p><p>Now you know a couple ways to make a textured sphere: that's the starting point for having a lot of fun with basic procedural planet, moon, or astroid generation! Here's some examples of things you can create based on these general ideas:</p>
Tim
https://au.mathworks.com/matlabcentral/profile/authors/4596244
tag:au.mathworks.com,2005:Topic/845993
2024-02-15T22:46:25Z
2024-02-20T15:54:48Z
Create hyperlinks in the command window
<p>The MATLAB command window isn't just for commands and outputsβit can also host interactive hyperlinks. These can serve as powerful shortcuts, enhancing the feedback you provide during code execution. Here are some hyperlinks I frequently use in fprintf statements, warnings, or error messages.
1. Open a website.
msg = "Could not download data from website.";
url = "https://blogs.mathworks.com/graphics-and-apps/";
hypertext = "Go to website"</p><p>fprintf(1,'%s <a href = "https://www.mathworks.com">href="matlab: web(''%s'') "</a>%s</a>\n',msg,url,hypertext);
Could not download data from website. Go to website</p><p>2. Open a folder in file explorer (Windows)
msg = "File saved to current directory.";
directory = cd();
hypertext = "[Open directory]";</p><p>fprintf(1,'%s <a href = "https://www.mathworks.com">href="matlab: winopen(''%s'') "</a>%s</a>\n',msg,directory,hypertext)
File saved to current directory. [Open directory]</p><p>3. Open a document (Windows)
msg = "Created database.csv.";
filepath = fullfile(cd,'database.csv');
hypertext = "[Open file]";</p><p>fprintf(1,'%s <a href = "https://www.mathworks.com">href="matlab: winopen(''%s'') "</a>%s</a>\n',msg,filepath,hypertext)
Created database.csv. [Open file]</p><p>4. Open an m-file and go to a specific line
msg = 'Go to';
file = 'streamline.m';
line = 51;
fprintf(1,'%s <a href = "https://www.mathworks.com">href="matlab: matlab.desktop.editor.openAndGoToLine(which(''%s''), %d); "</a>%s line %d</a>', msg, file, line, file, line);
Go to streamline.m line 51</p><p>5. Display more text
msg = 'Incomplete data detected.';
extendedInfo = '\tFilename: m32c4r28\n\tDate: 12/20/2014\n\tElectrode: (3,7)\n\tDepth: ???\n';
hypertext = '[Click for more info]';</p><p>warning('%s <a href = "https://www.mathworks.com">href="matlab: fprintf(''%s'') "</a>%s</a>', msg,extendedInfo,hypertext);
Warning: Incomplete data detected. [Click for more info] <a href = "https://www.mathworks.com">click</a>
Filename: m32c4r28
Date: 12/20/2014
Electrode: (3,7)
Depth: ???
6. Run a function
See Create Hyperlinks that Run Functions</p><p>Similarly, you can also add hyperlinks in figures and apps
uihyperlink (R2021a)
Create a hyperlink using text()</p>
Adam Danz
https://au.mathworks.com/matlabcentral/profile/authors/25613423
tag:au.mathworks.com,2005:Topic/845803
2024-02-14T15:39:27Z
2024-02-14T16:00:51Z
Happy Valentine's Day
<p>See code here in our community contest area.
And what do you do for Valentine's Day?</p>
Chen Lin
https://au.mathworks.com/matlabcentral/profile/authors/6682740
tag:au.mathworks.com,2005:Topic/845376
2024-02-10T13:59:09Z
2024-02-10T19:23:19Z
contact technical support
<p>which technical support should I contact/ask for the published Simscape example?</p>
K
https://au.mathworks.com/matlabcentral/profile/authors/9046909
tag:au.mathworks.com,2005:Topic/845276
2024-02-10T03:46:16Z
2024-02-10T03:46:16Z
Fun Spring Festival Couplets
<p>Happy year of the dragon.</p><img src = "/matlabcentral/discussions/uploaded_files/25976/data">
Chen Lin
https://au.mathworks.com/matlabcentral/profile/authors/6682740
tag:au.mathworks.com,2005:Topic/845271
2024-02-10T02:15:38Z
2024-02-29T22:14:05Z
Trick to enlarge a matrix by padding it with zeros.
<p>To enlarge an array with more rows and/or columns, you can set the lower right index to zero. This will pad the matrix with zeros.
m = rand(2, 3) % Initial matrix is 2 rows by 3 columns
mCopy = m;
% Now make it 2 rows by 5 columns
m(2, 5) = 0</p><p>m = mCopy; % Go back to original matrix.
% Now make it 3 rows by 3 columns
m(3, 3) = 0</p><p>m = mCopy; % Go back to original matrix.
% Now make it 3 rows by 7 columns
m(3, 7) = 0</p>
Image Analyst
https://au.mathworks.com/matlabcentral/profile/authors/1343420