主要内容

Results for


Speaking as someone with 31+ years of experience developing and using imshow, I want to advocate for retiring and replacing it.
The function imshow has behaviors and defaults that were appropriate for the MATLAB and computer monitors of the 1990s, but which are not the best choice for most image display situations in today's MATLAB. Also, the 31 years have not been kind to the imshow code base. It is a glitchy, hard-to-maintain monster.
My new File Exchange function, imview, illustrates the kind of changes that I think should be made. The function imview is a much better MATLAB graphics citizen and produces higher quality image display by default, and it dispenses with the whole fraught business of trying to resize the containing figure. Although this is an initial release that does not yet support all the useful options that imshow does, it does enough that I am prepared to stop using imshow in my own work.
The Image Processing Toolbox team has just introduced in R2024b a new image viewer called imageshow, but that image viewer is created in a special-purpose window. It does not satisfy the need for an image display function that works well with the axes and figure objects of the traditional MATLAB graphics system.
I have published a blog post today that describes all this in more detail. I'd be interested to hear what other people think.
Note: Yes, I know there is an Image Processing Toolbox function called imview. That one is a stub for an old toolbox capability that was removed something like 15+ years ago. The only thing the toolbox imview function does now is call error. I have just submitted a support request to MathWorks to remove this old stub.
The int function in the Symbolic Toolbox has a hold/release functionality wherein the expression can be held to delay evaluation
syms x I
eqn = I == int(x,x,'Hold',true)
eqn = 
which allows one to show the integral, and then use release to show the result
release(eqn)
ans = 
I think I already submitted an enhancement request for the same functionality for symsum.
Maybe it would be nice to be able to hold/release any symbolic expression to delay the engine from doing evaluations/simplifications that it typically does. For example:
x*(x+1)/x, sin(sym(pi)/3)
ans = 
ans = 
If I'm trying to show a sequence of steps to develop a result, maybe I want to explicitly keep the x/x in the first case and then say "now the x in the numerator and denominator cancel and the result is ..." followed by the release command to get the final result.
Perhaps held expressions could even be nested to show a sequence of results upon subsequent releases.
Held expressions might be subject to other limitations, like maybe they can't be fplotted.
Seems like such a capability might not be useful for problem solving, but might be useful for exposition, instruction, etc.
Watt's Up with Electric Vehicles?EV modeling Ecosystem (Eco-friendly Vehicles), V2V Communication and V2I communications thereby emitting zero Emissions to considerably reduce NOx ,Particulates matters,CO2 given that Combustion is always incomplete and will always be.
Reduction of gas emissions outside to the environment will improve human life span ,few epidemic diseases and will result in long life standard
Hi! My name is Mike McLernon, and I’m a product marketing engineer with MathWorks. In my role, I look at the trends ongoing in the wireless industry, across lots of different standards (think 5G, WLAN, SatCom, Bluetooth, etc.), and I seek to shape and guide the software that MathWorks builds to respond to these trends. That’s all about communicating within the Mathworks organization, but every so often it’s worth communicating these trends to our audience in the world at large. Many of the people reading this are engineers (or engineers at heart), and we all want to know what’s happening in the geek world around us. I think that now is one of these times to communicate an important milestone. So, without further ado . . .
Bluetooth 6.0 is here! Announced in September by the Bluetooth Special Interest Group (SIG), it’s making more advances in its quest to create a “world without wires”. A few of the salient features in Bluetooth 6.0 are:
  1. Channel sounding (for accurate distance measurements)
  2. Decision-based advertising filtering (for more efficient channel scanning)
  3. Monitoring advertisers (for improved energy efficiency when devices come into and go out of range)
  4. Frame space updates (for both higher throughput and better coexistence management)
Bluetooth 6.0 includes other features as well, but the SIG has put special promotional emphasis on channel sounding (CS), which once upon a time was called High Accuracy Distance Measurement (HADM). The SIG has said that CS is a step towards true distance awareness, and 10 cm ranging accuracy. I think their emphasis is in exactly the right place, so let’s learn more about this technology and how it is used.
CS can be used for the following use cases:
  1. Keyless vehicle entry, performed by communication between a key fob or phone and the car’s anchor points
  2. Smart locks, to permit access only when an authorized device is within a designated proximity to the locks
  3. Geofencing, to limit access to designated areas
  4. Warehouse management, to monitor inventory and manage logistics
  5. Asset tracking for virtually any object of interest
In the past, Bluetooth devices would use a received signal strength indicator (RSSI) measurement to infer the distance between two of them. They would assume a free space path loss on the link, and use a straightforward equation to estimate distance:
where
received power in dBm,
transmitted power in dBm,
propagation loss in dB,
distance between the two devices, in m,
Bluetooth signal wavelength, in m,
Bluetooth signal frequency, in Hz,
speed of light (3 x 1e8 m/s).
So in this method, . But if the signal suffers more loss from multipath or shadowing, then the distance would be overestimated. Something better needed to be found.
Bluetooth 6.0 introduces not one, but two ways to accurately measure distance:
  1. Round-trip time (RTT) measurement
  2. Phase-based ranging (PBR) measurement
The RTT measurement method uses the fact that the Bluetooth signal time of flight (TOF) between two devices is half the RTT. It can then accurately compute the distance d as
, where c is again the speed of light. This method requires accurate measurements of the time of departure (TOD) of the outbound signal from device 1 (the Initiator), time of arrival (TOA) of the outbound signal to device 2 (the Reflector), TOD of the return signal from device 2, and TOA of the return signal to device 1. The diagram below shows the signal paths and the times.
If you want to see how you can use MATLAB to simulate the RTT method, take a look at Estimate Distance Between Bluetooth LE Devices by Using Channel Sounding and Round-Trip Timing.
The PBR method uses two Bluetooth signals of different frequencies to measure distance. These signals are simply tones – sine waves. Without going through the derivation, PBR calculates distance d as
, where
distance between the two devices, in m,
speed of light (3 x 1e8 m/s),
phase measured at the Initiator after the tone at completes a round trip, in radians,
phase measured at the Initiator after the tone at completes a round trip, in radians,
frequency of the first tone, in Hz,
frequency of the second tone, in Hz.
The mod() operation is needed to eliminate ambiguities in the distance calculation and the final division by two is to convert a round trip distance to a one-way distance. Because a given phase difference value can hold true for an infinite number of distance values, the mod() operation chooses the smallest distance that satisfies the equation. Also, these tones can be as close as 1 MHz apart. In that case, the maximum resolvable distance measurement is about 150 m. The plot below shows that ambiguity and repetition in distance measurement.
If you want to see how you can use MATLAB to simulate the PBR method, take a look at Estimate Distance Between Bluetooth LE Devices by Using Channel Sounding and Phase-Based Ranging.
Bluetooth 6.0 outlines RTT and PBR distance measurement methods, but CS does not mandate a specific algorithm for calculating distance estimates. This flexibility allows device manufacturers to tailor solutions to various use cases, balancing computational complexity with required accuracy and adapting to different radio environments. Examples include simple phase difference calculations and FFT-based methods.
Although Bluetooth 6.0 is now out, it is far from a finished version. The SIG is actively working through the ratification process for two major extensions:
  1. High Data Throughput, up to 8 Mbps
  2. 5 and 6 GHz operation
See the last few minutes of this video from the SIG to learn more about these exciting future developments. And if you want to see more Bluetooth blogs, give a review of this one! Finally, if you have specific Bluetooth questions, give me a shout and let’s start a discussion!
Image Analyst
Image Analyst
Last activity 2024-12-2,22:14

Christmas season is underway at my house:
(Sorry - the ornament is not available at the MathWorks Merch Shop -- I made it with a 3-D printer.)
So I made this.
clear
close all
clc
% inspired from: https://www.youtube.com/watch?v=3CuUmy7jX6k
%% user parameters
h = 768;
w = 1024;
N_snowflakes = 50;
%% set figure window
figure(NumberTitle="off", ...
name='Mat-snowfalling-lab (right click to stop)', ...
MenuBar="none")
ax = gca;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
axis equal
axis([0, w, 0, h])
ax.Color = 'k';
ax.XAxis.Visible = 'off';
ax.YAxis.Visible = 'off';
ax.Position = [0, 0, 1, 1];
%% first snowflake
ht = gobjects(1, 1);
for i=1:length(ht)
ht(i) = hgtransform();
ht(i).UserData = snowflake_factory(h, w);
ht(i).Matrix(2, 4) = ht(i).UserData.y;
ht(i).Matrix(1, 4) = ht(i).UserData.x;
im = imagesc(ht(i), ht(i).UserData.img);
im.AlphaData = ht(i).UserData.alpha;
colormap gray
end
%% falling snowflake
tic;
while true
% add a snowflake every 0.3 seconds
if toc > 0.3
if length(ht) < N_snowflakes
ht = [ht; hgtransform()];
ht(end).UserData = snowflake_factory(h, w);
ht(end).Matrix(2, 4) = ht(end).UserData.y;
ht(end).Matrix(1, 4) = ht(end).UserData.x;
im = imagesc(ht(end), ht(end).UserData.img);
im.AlphaData = ht(end).UserData.alpha;
colormap gray
end
tic;
end
ax.CLim = [0, 0.0005]; % prevent from auto clim
% move snowflakes
for i = 1:length(ht)
ht(i).Matrix(2, 4) = ht(i).Matrix(2, 4) + ht(i).UserData.velocity;
end
if strcmp(get(gcf, 'SelectionType'), 'alt')
set(gcf, 'SelectionType', 'normal')
break
end
drawnow
% delete the snowflakes outside the window
for i = length(ht):-1:1
if ht(i).Matrix(2, 4) < -length(ht(i).Children.CData)
delete(ht(i))
ht(i) = [];
end
end
end
%% snowflake factory
function snowflake = snowflake_factory(h, w)
radius = round(rand*h/3 + 10);
sigma = radius/6;
snowflake.velocity = -rand*0.5 - 0.1;
snowflake.x = rand*w;
snowflake.y = h - radius/3;
snowflake.img = fspecial('gaussian', [radius, radius], sigma);
snowflake.alpha = snowflake.img/max(max(snowflake.img));
end
We are thrilled to announce the grand prize winners of our MATLAB Shorts Mini Hack contest! This year, we invited the MATLAB Graphics and Charting team, the authors of the MATLAB functions used in every entry, to be our judges. After careful consideration, they have selected the top three winners:
1st place - Tim
Judge comments: Realism & detailed comments; wowed us with Manta Ray
2nd place – Jenny Bosten
Judge comments: Topical hacks : Auroras & Wind turbine; beautiful landscapes & nightscapes
3rd place - Vasilis Bellos
Judge comments: Nice algorithms & extra comments; can’t go wrong with Pumpkins
There is also an Honorable Mention - William Dean
Judge comments: Impressive spring & cubes!
In addition, after validating the votes, we are pleased to announce the top 10 participants on the leaderboard:
Congratulations to all! Your creativity and skills have inspired many of us to explore and learn new skills, and make this contest a big success!
Dear MATLAB contest enthusiasts,
Welcome to the third installment of our interview series with top contest participants! This time we had the pleasure of talking to our all-time rock star – @Jenny Bosten. Every one of her entries is a masterpiece, demonstrating a deep understanding of the relationship between mathematics and aesthetics. Even Cleve Moler, the original author of MATLAB, is impressed and wrote in his blog: "Her code for Time Lapse of Lake View to the West shows she is also a wizard of coordinate systems and color maps."
The interview has been published on the MATLAB Community Blog. We highly encourage
you to read it to learn more about Jenny’s journey, her creative process, and her favorite entries.
Question: Who would you like to see featured in our next interview? Let us know your thoughts in the comments!
It would be nice to have a function to shade between two curves. This is a common question asked on Answers and there are some File Exchange entries on it but it's such a common thing to want to do I think there should be a built in function for it. I'm thinking of something like
plotsWithShading(x1, y1, 'r-', x2, y2, 'b-', 'ShadingColor', [.7, .5, .3], 'Opacity', 0.5);
So we can specify the coordinates of the two curves, and the shading color to be used, and its opacity, and it would shade the region between the two curves where the x ranges overlap. Other options should also be accepted, like line with, line style, markers or not, etc. Perhaps all those options could be put into a structure as fields, like
plotsWithShading(x1, y1, options1, x2, y2, options2, 'ShadingColor', [.7, .5, .3], 'Opacity', 0.5);
the shading options could also (optionally) be a structure. I know it can be done with a series of other functions like patch or fill, but it's kind of tricky and not obvious as we can see from the number of questions about how to do it.
Does anyone else think this would be a convenient function to add?
Over the past 4 weeks, 250+ creative short movies have been crafted. We had a lot of fun and, more importantly, learned new skills from each other! Now it’s time to announce week 4 winners.
Nature:
3D:
Seamless loop:
Holiday:
Fractal:
Congratulations! Each of you won your choice of a T-shirt, a hat, or a coffee mug. We will contact you after the contest ends.
Weekly Special Prizes
Thank you for sharing your tips & tricks with the community. These great technical articles will benefit community users for many years. You won a limited-edition pair of MATLAB Shorts!
In week 5, let’s take a moment to sit back, explore all of the interesting entries, and cast your votes. Reflect what you have learned or which entries you like most. Share anything in our Discussions area! There is still time to win our limited-edition MATLAB Shorts.
In the past two years, large language models have brought us significant changes, leading to the emergence of programming tools such as GitHub Copilot, Tabnine, Kite, CodeGPT, Replit, Cursor, and many others. Most of these tools support code writing by providing auto-completion, prompts, and suggestions, and they can be easily integrated with various IDEs.
As far as I know, aside from the MATLAB-VSCode/MatGPT plugin, MATLAB lacks such AI assistant plugins for its native MATLAB-Desktop, although it can leverage other third-party plugins for intelligent programming assistance. There is hope for a native tool of this kind to be built-in.
Hi everyone, I wrote several fancy functions that may help your coding experience, since they are in very early developing stage, I will be thankful if anyone could try them and give some feedbacks. Currently I have following:
  • fstr: a Python f-string like expression
  • printf: an easy to use fprintf function, accepts multiple arguments with seperator, end string control.
I will bring more functions or packages like logger when I am available.
The code is open sourced at GitHub with simple examples: https://github.com/bentrainer/MMGA
MATLAB Comprehensive commands list:
  • clc - clears command window, workspace not affected
  • clear - clears all variables from workspace, all variable values are lost
  • diary - records into a file almost everything that appears in command window.
  • exit - exits the MATLAB session
  • who - prints all variables in the workspace
  • whos - prints all variables in current workspace, with additional information.
Ch. 2 - Basics:
  • Mathematical constants: pi, i, j, Inf, Nan, realmin, realmax
  • Precedence rules: (), ^, negation, */, +-, left-to-right
  • and, or, not, xor
  • exp - exponential
  • log - natural logarithm
  • log10 - common logarithm (base 10)
  • sqrt (square root)
  • fprintf("final amount is %f units.", amt);
  • can have: %f, %d, %i, %c, %s
  • %f - fixed-point notation
  • %e - scientific notation with lowercase e
  • disp - outputs to a command window
  • % - fieldWith.precision convChar
  • MyArray = [startValue : IncrementingValue : terminatingValue]
Linspace
linspace(xStart, xStop, numPoints)
% xStart: Starting value
% xStop: Stop value
% numPoints: Number of linear-spaced points, including xStart and xStop
% Outputs a row array with the resulting values
Logspace
logspace(powerStart, powerStop, numPoints)
% powerStart: Starting value 10^powerStart
% powerStop: Stop value 10^powerStop
% numPoints: Number of logarithmic spaced points, including 10^powerStart and 10^powerStop
% Outputs a row array with the resulting values
  • Transpose an array with []'
Element-Wise Operations
rowVecA = [1, 4, 5, 2];
rowVecB = [1, 3, 0, 4];
sumEx = rowVecA + rowVecB % Element-wise addition
diffEx = rowVecA - rowVecB % Element-wise subtraction
dotMul = rowVecA .* rowVecB % Element-wise multiplication
dotDiv = rowVecA ./ rowVecB % Element-wise division
dotPow = rowVecA .^ rowVecB % Element-wise exponentiation
  • isinf(A) - check if the array elements are infinity
  • isnan(A)
Rounding Functions
  • ceil(x) - rounds each element of x to nearest integer >= to element
  • floor(x) - rounds each element of x to nearest integer <= to element
  • fix(x) - rounds each element of x to nearest integer towards 0
  • round(x) - rounds each element of x to nearest integer. if round(x, N), rounds N digits to the right of the decimal point.
  • rem(dividend, divisor) - produces a result that is either 0 or has the same sign as the dividen.
  • mod(dividend, divisor) - produces a result that is either 0 or same result as divisor.
  • Ex: 12/2, 12 is dividend, 2 is divisor
  • sum(inputArray) - sums all entires in array
Complex Number Functions
  • abs(z) - absolute value, is magnitude of complex number (phasor form r*exp(j0)
  • angle(z) - phase angle, corresponds to 0 in r*exp(j0)
  • complex(a,b) - creates complex number z = a + jb
  • conj(z) - given complex conjugate a - jb
  • real(z) - extracts real part from z
  • imag(z) - extracts imaginary part from z
  • unwrap(z) - removes the modulus 2pi from an array of phase angles.
Statistics Functions
  • mean(xAr) - arithmetic mean calculated.
  • std(xAr) - calculated standard deviation
  • median(xAr) - calculated the median of a list of numbers
  • mode(xAr) - calculates the mode, value that appears most often
  • max(xAr)
  • min(xAr)
  • If using &&, this means that if first false, don't bother evaluating second
Random Number Functions
  • rand(numRand, 1) - creates column array
  • rand(1, numRand) - creates row array, both with numRand elements, between 0 and 1
  • randi(maxRandVal, numRan, 1) - creates a column array, with numRand elements, between 1 and maxRandValue.
  • randn(numRand, 1) - creates a column array with normally distributed values.
  • Ex: 10 * rand(1, 3) + 6
  • "10*rand(1, 3)" produces a row array with 3 random numbers between 0 and 10. Adding 6 to each element results in random values between 6 and 16.
  • randi(20, 1, 5)
  • Generates 5 (last argument) random integers between 1 (second argument) and 20 (first argument). The arguments 1 and 5 specify a 1 × 5 row array is returned.
Discrete Integer Mathematics
  • primes(maxVal) - returns prime numbers less than or equal to maxVal
  • isprime(inputNums) - returns a logical array, indicating whether each element is a prime number
  • factor(intVal) - returns the prime factors of a number
  • gcd(aVals, bVals) - largest integer that divides both a and b without a remainder
  • lcm(aVals, bVals) - smallest positive integer that is divisible by both a and b
  • factorial(intVals) - returns the factorial
  • perms(intVals) - returns all the permutations of the elements int he array intVals in a 2D array pMat.
  • randperm(maxVal)
  • nchoosek(n, k)
  • binopdf(x, n, p)
Concatenation
  • cat, vertcat, horzcat
  • Flattening an array, becomes vertical: sampleList = sampleArray ( : )
Dimensional Properties of Arrays
  • nLargest = length(inArray) - number of elements along largest dimension
  • nDim = ndims(inArray)
  • nArrElement = numel(inArray) - nuber of array elements
  • [nRow, nCol] = size(inArray) - returns the number of rows and columns on array. use (inArray, 1) if only row, (inArray, 2) if only column needed
  • aZero = zeros(m, n) - creates an m by n array with all elements 0
  • aOnes = ones(m, n) - creates an m by n array with all elements set to 1
  • aEye = eye(m, n) - creates an m by n array with main diagonal ones
  • aDiag = diag(vector) - returns square array, with diagonal the same, 0s elsewhere.
  • outFlipLR = fliplr(A) - Flips array left to right.
  • outFlipUD = flipud(A) - Flips array upside down.
  • outRot90 = rot90(A) - Rotates array by 90 degrees counter clockwise around element at index (1,1).
  • outTril = tril(A) - Returns the lower triangular part of an array.
  • outTriU = triu(A) - Returns the upper triangular part of an array.
  • arrayOut = repmat(subarrayIn, mRow, nCol), creates a large array by replicating a smaller array, with mRow x nCol tiling of copies of subarrayIn
  • reshapeOut - reshape(arrayIn, numRow, numCol) - returns array with modifid dimensions. Product must equal to arrayIn of numRow and numCol.
  • outLin = find(inputAr) - locates all nonzero elements of inputAr and returns linear indices of these elements in outLin.
  • [sortOut, sortIndices] = sort(inArray) - sorts elements in ascending order, results result in sortOut. specify 'descend' if you want descending order. sortIndices hold the sorted indices of the array elements, which are row indices of the elements of sortOut in the original array
  • [sortOut, sortIndices] = sortrows(inArray, colRef) - sorts array based on values in column colRef while keeping the rows together. Bases on first column by default.
  • isequal(inArray1, inarray2, ..., inArrayN)
  • isequaln(inArray1, inarray2, ..., inarrayn)
  • arrayChar = ischar(inArray) - ischar tests if the input is a character array.
  • arrayLogical = islogical(inArray) - islogical tests for logical array.
  • arrayNumeric = isnumeric(inArray) - isnumeric tests for numeric array.
  • arrayInteger = isinteger(inArray) - isinteger tests whether the input is integer type (Ex: uint8, uint16, ...)
  • arrayFloat = isfloat(inArray) - isfloat tests for floating-point array.
  • arrayReal= isreal(inArray) - isreal tests for real array.
  • objIsa = isa(obj,ClassName) - isa determines whether input obj is an object of specified class ClassName.
  • arrayScalar = isscalar(inArray) - isscalar tests for scalar type.
  • arrayVector = isvector(inArray) - isvector tests for a vector (a 1D row or column array).
  • arrayColumn = iscolumn(inArray) - iscolumn tests for column 1D arrays.
  • arrayMatrix = ismatrix(inArray) - ismatrix returns true for a scalar or array up to 2D, but false for an array of more than 2 dimensions.
  • arrayEmpty = isempty(inArray) - isempty tests whether inArray is empty.
  • primeArray = isprime(inArray) - isprime returns a logical array primeArray, of the same size as inArray. The value at primeArray(index) is true when inArray(index) is a prime number. Otherwise, the values are false.
  • finiteArray = isfinite(inArray) - isfinite returns a logical array finiteArray, of the same size as inArray. The value at finiteArray(index) is true when inArray(index) is finite. Otherwise, the values are false.
  • infiniteArray = isinf(inArray) - isinf returns a logical array infiniteArray, of the same size as inArray. The value at infiniteArray(index) is true when inArray(index) is infinite. Otherwise, the values are false.
  • nanArray = isnan(inArray) - isnan returns a logical array nanArray, of the same size as inArray. The value at nanArray(index) is true when inArray(index) is NaN. Otherwise, the values are false.
  • allNonzero = all(inArray) - all identifies whether all array elements are non-zero (true). Instead of testing elements along the columns, all(inArray, 2) tests along the rows. all(inArray,1) is equivalent to all(inArray).
  • anyNonzero = any(inArray) - any identifies whether any array elements are non-zero (true), and false otherwise. Instead of testing elements along the columns, any(inArray, 2) tests along the rows. any(inArray,1) is equivalent to any(inArray).
  • logicArray = ismember(inArraySet,areElementsMember) - ismember returns a logical array logicArray the same size as inArraySet. The values at logicArray(i) are true where the elements of the first array inArraySet are found in the second array areElementsMember. Otherwise, the values are false. Similar values found by ismember can be extracted with inArraySet(logicArray).
  • any(x) - Returns true if x is nonzero; otherwise, returns false.
  • isnan(x) - Returns true if x is NaN (Not-a-Number); otherwise, returns false.
  • isfinite(x) - Returns true if x is finite; otherwise, returns false. Ex: isfinite(Inf) is false, and isfinite(10) is true.
  • isinf(x) - Returns true if x is +Inf or -Inf; otherwise, returns false.
Relational Operators
a < b - a is less than b
a > b - a is greater than b
a <= b - a is less than or equal to b
a >= b - a is greater than or equal to b
a == b - a is equal to b
a ~= b - a is not equal to b
a & b, and(a, b)
a | b, or(a, b)
~a, not(a)
xor(a, b)
  • fctName = @(arglist) expression - anonymous function
  • nargin - keyword returns the number of input arguments passed to the function.
Looping
while condition
% code
end
for index = startVal:endVal
% code
end
  • continue: Skips the rest of the current loop iteration and begins the next iteration.
  • break: Exits a loop before it has finished all iterations.
switch expression
case value1
% code
case value2
% code
otherwise
% code
end
Comprehensive Overview (may repeat)
Built in functions/constants
abs(x) - absolute value
pi - 3.1415...
inf - ∞
eps - floating point accuracy 1e6 106
sum(x) - sums elements in x
cumsum(x) - Cumulative sum
prod - Product of array elements cumprod(x) cumulative product
diff - Difference of elements round/ceil/fix/floor Standard functions..
*Standard functions: sqrt, log, exp, max, min, Bessel *Factorial(x) is only precise for x < 21
Variable Generation
j:k - row vector
j:i:k - row vector incrementing by i
linspace(a,b,n) - n points linearly spaced and including a and b
NaN(a,b) - axb matrix of NaN values
ones(a,b) - axb matrix with all 1 values
zeros(a,b) - axb matrix with all 0 values
meshgrid(x,y) - 2d grid of x and y vectors
global x
Ch. 11 - Custom Functions
function [ outputArgs ] = MainFunctionName (inputArgs)
% statements go here
end
function [ outputArgs ] = LocalFunctionName (inputArgs)
% statements go here
end
  • You are allowed to have nested functions in MATLAB
Anonymous Function:
  • fctName = @(argList) expression
  • Ex: RaisedCos = @(angle) (cosd(angle))^2;
  • global variables - can be accessed from anywhere in the file
  • Persistent variables
  • persistent variable - only known to function where it was declared, maintains value between calls to function.
  • Recursion - base case, decreasing case, ending case
  • nargin - evaluates to the number of arguments the function was called with
Ch. 12 - Plotting
  • plot(xArray, yArray)
  • refer to help plot for more extensive documentation, chapter 12 only briefly covers plotting
plot - Line plot
yyaxis - Enables plotting with y-axes on both left and right sides
loglog - Line plot with logarithmic x and y axes
semilogy - Line plot with linear x and logarithmic y axes
semilogx - Line plot with logarithmic x and linear y axes
stairs - Stairstep graph
axis - sets the aspect ratio of x and y axes, ticks etc.
grid - adds a grid to the plot
gtext - allows positioning of text with the mouse
text - allows placing text at specified coordinates of the plot
xlabel labels the x-axis
ylabel labels the y-axis
title sets the graph title
figure(n) makes figure number n the current figure
hold on allows multiple plots to be superimposed on the same axes
hold off releases hold on current plot and allows a new graph to be drawn
close(n) closes figure number n
subplot(a, b, c) creates an a x b matrix of plots with c the current figure
orient specifies the orientation of a figure
Animated plot example:
for j = 1:360
pause(0.02)
plot3(x(j),y(j),z(j),'O')
axis([minx maxx miny maxy minz maxz]);
hold on;
end
Ch. 13 - Strings
stringArray = string(inputArray) - converts the input array inputArray to a string array
number = strLength(stringIn) - returns the number of characters in the input string
stringArray = strings(n, m) - returns an n-by-m array of strings with no characters,
  • doing strings(sz) returns an array of strings with no characters, where sz defines the size.
charVec1 = char(stringScalar) char(stringScalar) converts the string scalar stringScalar into a character vector charVec1.
charVec2 = char(numericArray) char(numericArray) converts the numeric array numericArray into a character vector charVec2 corresponding to the Unicode transformation format 16 (UTF-16) code.
stringOut = string1 + string2 - combines the text in both strings
stringOut = join(textSrray) - consecutive elements of array joined, placing a space character between them.
stringOut = blanks(n) - creates a string of n blank characters
stringOut = strcar(string1, string2) - horizontally concatenates strings in arrays.
sprintf(formatSpec, number) - for printing out strings
  • strExp = sprintf("%0.6e", pi)
stringArrayOur = compose(formatSpec, arrayIn) - formats data in arrayIn.
lower(string) - converts to lowercase
upper(string) - converts to uppercase
num2str(inputArray, precision) - returns a character vector with the maximum number of digits specified by precision
mat2str(inputMat, precision), converts matrix into a character vector.
numberOut = sscanf(inputText, format) - convert inputText according to format specifier
str2double(inputText)
str2num(inputChar)
strcmp(string1, string2)
strcmpi(string1, string2) - case-insensitive comparison
strncmp(str1, str2, n) - first n characters
strncmpi(str1, str2, n) - case-insensitive comparison of first n characters.
isstring(string) - logical output
isStringScalar(string) - logical output
ischar(inputVar) - logical output
iscellstr(inputVar) - logical output.
isstrprop(stringIn, categoryString) - returns a logical array of the same size as stringIn, with true at indices where elements of the stringIn belong to specified category:
iskeyword(stringIn) - returns true if string is a keyword in the matlab language
isletter(charVecIn)
isspace(charVecIn)
ischar(charVecIn)
contains(string1, testPattern) - boolean outputs if string contains a specific pattern
startsWith(string1, testPattern) - also logical output
endsWith(string1, testPattern) - also logical output
strfind(stringIn, pattern) - returns INDEX of each occurence in array
number = count(stringIn, patternSeek) - returns the number of occurences of string scalar in the string scalar stringIn.
strip(strArray) - removes all consecutive whitespace characters from begining and end of each string in Array, with side argument 'left', 'right', 'both'.
pad(stringIn) - pad with whitespace characters, can also specify where.
replace(stringIn, oldStr, newStr) - replaces all occurrences of oldStr in string array stringIn with newStr.
replaceBetween(strIn, startStr, endStr, newStr)
strrep(origStr, oldSubsr, newSubstr) - searches original string for substric, and if found, replace with new substric.
insertAfter(stringIn, startStr, newStr) - insert a new string afte the substring specified by startStr.
insertBefore(stringIn, endPos, newStr)
extractAfter(stringIn, startStr)
extractBefore(stringIn, startPos)
split(stringIn, delimiter) - divides string at whitespace characters.
splitlines(stringIn, delimiter)
I know we have all been in that all-too-common situation of needing to inefficiently identify prime numbers using only a regular expression... and now Matt Parker from Standup Maths helpfully released a YouTube video entitled "How on Earth does ^.?$|^(..+?)\1+$ produce primes?" in which he explains a simple regular expression (aka Halloween incantation) which matches composite numbers:
Here is my first attempt using MATLAB and Matt Parker's example values:
fnh = @(n) isempty(regexp(repelem('*',n),'^.?$|^(..+?)\1+$','emptymatch'));
fnh(13)
ans = logical
1
fnh(15)
ans = logical
0
fnh(101)
ans = logical
1
fnh(1000)
ans = logical
0
Feel free to try/modify the incantation yourself. Happy Halloween!
It's frustrating when a long function or script runs and prints unexpected outputs to the command window. The line producing those outputs can be difficult to find.
Starting in R2024b, use dbstop to find the line with unsuppressed outputs!
Run this line of code before running the script or function. Execution will pause when the line is hit and the file will open to that line. Outputs that are intentionaly displayed by functions such as disp() or fprintf() will be ignored.
dbstop if unsuppressed output
To turn this off,
dbclear if unsuppressed output
We are thrilled to see the incredible short movies created during Week 3. The bar has been set exceptionally high! This week, we invited our Community Advisory Board (CAB) members to select winners. Here are their picks:
Mini Hack Winners - Week 3
Game:
Holidays:
Fractals:
Realism:
Great Remixes:
Seamless loop:
Fun:
Weekly Special Prizes
Special shoutout to @Vasilis Bellos. This article was featured on the MATLAB Blog.
Thank you for sharing your tips & tricks with the community. You won a limited-edition MATLAB Shorts.
We still have plenty of MATLAB Shorts available, so be sure to create your posts before the contest ends. Don't miss out on the opportunity to showcase your creativity!
Time to time I need to filll an existing array with NaNs using logical indexing. A trick I discover is using arithmetics rather than filling. It is quite faster in some circumtances
A=rand(10000);
b=A>0.5;
tic; A(b) = NaN; toc
Elapsed time is 0.737291 seconds.
tic; A = A + 0./~b; toc;
Elapsed time is 0.027666 seconds.
If you know trick for other value filling feel free to post.