メインコンテンツ

結果:

goc3
goc3
最後のアクティビティ: 37分 前

Untapped Potential for Output-arguments Block
MATLAB has a very powerful feature in its arguments blocks. For example, the following code for a function (or method):
  • clearly outlines all the possible inputs
  • provides default values for each input
  • will produce auto-complete suggestions while typing in the Editor (and Command Window in newer versions)
  • checks each input against validation functions to enforce size, shape (e.g., column vs. row vector), type, and other options (e.g., being a member of a set)
function [out] = sample_fcn(in)
arguments(Input)
in.x (:, 1) = []
in.model_type (1, 1) string {mustBeMember(in.model_type, ...
["2-factor", "3-factor", "4-factor"])} = "2-factor"
in.number_of_terms (1, 1) {mustBeMember(in.number_of_terms, 1:5)} = 1
in.normalize_fit (1, 1) logical = false
end
% function logic ...
end
If you do not already use the arguments block for function (or method) inputs, I strongly suggest that you try it out.
The point of this post, though, is to suggest improvements for the output-arguments block, as it is not nearly as powerful as its input-arguments counterpart. I have included two function examples: the first can work in MATLAB while the second does not, as it includes suggestions for improvements. Commentary specific to each function is provided completely before the code. While this does necessitate navigating back and forth between functions and text, this provides for an easy comparison between the two functions which is my main goal.
Current Implementation
The input-arguments block for sample_fcn begins the function and has already been discussed. A simple output-arguments block is also included. I like to use a single output so that additional fields may be added at a later point. Using this approach simplifies future development, as the function signature, wherever it may be used, does not need to be changed. I can simply add another output field within the function and refer to that additional field wherever the function output is used.
Before beginning any logic, sample_fcn first assigns default values to four fields of out. This is a simple and concise way to ensure that the function will not error when returning early.
The function then performs two checks. The first is for an empty input (x) vector. If that is the case, nothing needs to be done, as the function simply returns early with the default output values that happen to apply to the inability to fit any data.
The second check is for edge cases for which input combinations do not work. In this case, the status is updated, but default values for all other output fields (which are already assigned) still apply, so no additional code is needed.
Then, the function performs the fit based on the specified model_type. Note that an otherwise case is not needed here, since the argument validation for model_type would not allow any other value.
At this point, the total_error is calculated and a check is then made to determine if it is valid. If not, the function again returns early with another specific status value.
Finally, the R^2 value is calculated and a fourth check is performed. If this one fails, another status value is assigned with an early return.
If the function has passed all the checks, then a set of assertions ensure that each of the output fields are valid. In this case, there are eight specific checks, two for each field.
If all of the assertions also pass, then the final (successful) status is assigned and the function returns normally.
function [out] = sample_fcn(in)
arguments(Input)
in.x (:, 1) = []
in.model_type (1, 1) string {mustBeMember(in.model_type, ...
["2-factor", "3-factor", "4-factor"])} = "2-factor"
in.number_of_terms (1, 1) {mustBeMember(in.number_of_terms, 1:5)} = 1
in.normalize_fit (1, 1) logical = false
end
arguments(Output)
out struct
end
%%
out.fit = [];
out.total_error = [];
out.R_squared = NaN;
out.status = "Fit not possible for supplied inputs.";
%%
if isempty(in.x)
return
end
%%
if ((in.model_type == "2-factor") && (in.number_of_terms == 5)) || ... % other possible logic
out.status = "Specified combination of model_type and number_of_terms is not supported.";
return
end
%%
switch in.model_type
case "2-factor"
out.fit = % code for 2-factor fit
case "3-factor"
out.fit = % code for 3-factor fit
case "4-factor"
out.fit = % code for 4-factor fit
end
%%
out.total_error = % calculation of error
if ~isfinite(out.total_error)
out.status = "The total_error could not be calculated.";
return
end
%%
out.R_squared = % calculation of R^2
if out.R_squared > 1
out.status = "The R^2 value is out of bounds.";
return
end
%%
assert(iscolumn(out.fit), "The fit vector is not a column vector.");
assert(size(out.fit) == size(in.x), "The fit vector is not the same size as the input x vector.");
assert(isscalar(out.total_error), "The total_error is not a scalar.");
assert(isfinite(out.total_error), "The total_error is not finite.");
assert(isscalar(out.R_squared), "The R^2 value is not a scalar.");
assert(isfinite(out.R_squared), "The R^2 value is not finite.");
assert(isscalar(out.status), "The status is not a scalar.");
assert(isstring(out.status), "The status is not a string.");
%%
out.status = "The fit was successful.";
end
Potential Implementation
The second function, sample_fcn_output_arguments, provides essentially the same functionality in about half the lines of code. It is also much clearer with respect to the output. As a reminder, this function structure does not currently work in MATLAB, but hopefully it will in the not-too-distant future.
This function uses the same input-arguments block, which is then followed by a comparable output-arguments block. The first unsupported feature here is the use of name-value pairs for outputs. I would much prefer to make these assignments here rather than immediately after the block as in the sample_fcn above, which necessitates four more lines of code.
The mustBeSameSize validation function that I use for fit does not exist, but I really think it should; I would use it a lot. In this case, it provides a very succinct way of ensuring that the function logic did not alter the size of the fit vector from what is expected.
The mustBeFinite validation function for out.total_error does not work here simply because of the limitation on name-value pairs; it does work for regular outputs.
Finally, the assignment of default values to output arguments is not supported.
The next three sections of sample_fcn_output_arguments match those of sample_fcn: check if x is empty, check input combinations, and perform fit logic. Following that, though, the functions diverge heavily, as you might expect. The two checks for total_error and R^2 are not necessary, as those are covered by the output-arguments block. While there is a slight difference, in that the specific status values I assigned in sample_fcn are not possible, I would much prefer to localize all these checks in the arguments block, as is already done for input arguments.
Furthermore, the entire section of eight assertions in sample_fcn is removed, as, again, that would be covered by the output-arguments block.
This function ends with the same status assignment. Again, this is not exactly the same as in sample_fcn, since any failed assertion would prevent that assignment. However, that would also halt execution, so it is a moot point.
function [out] = sample_fcn_output_arguments(in)
arguments(Input)
in.x (:, 1) = []
in.model_type (1, 1) string {mustBeMember(in.model_type, ...
["2-factor", "3-factor", "4-factor"])} = "2-factor"
in.number_of_terms (1, 1) {mustBeMember(in.number_of_terms, 1:5)} = 1
in.normalize_fit (1, 1) logical = false
end
arguments(Output)
out.fit (:, 1) {mustBeSameSize(out.fit, in.x)} = []
out.total_error (1, 1) {mustBeFinite(out.total_error)} = []
out.R_squared (1, 1) {mustBeLessThanOrEqual(out.R_squared, 1)} = NaN
out.status (1, 1) string = "Fit not possible for supplied inputs."
end
%%
if isempty(in.x)
return
end
%%
if ((in.model_type == "2-factor") && (in.number_of_terms == 5)) || ... % other possible logic
out.status = "Specified combination of model_type and number_of_terms is not supported.";
return
end
%%
switch in.model_type
case "2-factor"
out.fit = % code for 2-factor fit
case "3-factor"
out.fit = % code for 3-factor fit
case "4-factor"
out.fit = % code for 4-factor fit
end
%%
out.status = "The fit was successful.";
end
Final Thoughts
There is a significant amount of unrealized potential for the output-arguments block. Hopefully what I have provided is helpful for continued developments in this area.
What are your thoughts? How would you improve arguments blocks for outputs (or inputs)? If you do not already use them, I hope that you start to now.
goc3
goc3
最後のアクティビティ: 2025 年 4 月 6 日

No
50%
Yes, but I am not interested
8%
Yes, but it is too expensive
20%
Yes, I would like to know more
18%
Yes, I am cert. MATLAB Associate
2%
Yes, I am cert. MATLAB Professional
3%
4779 票
goc3
goc3
最後のアクティビティ: 2025 年 2 月 11 日

Too small
22%
Just right
38%
Too large
40%
2648 票
goc3
goc3
最後のアクティビティ: 2024 年 12 月 3 日

I was browsing the MathWorks website and decided to check the Cody leaderboard. To my surprise, William has now solved 5,000 problems. At the moment, there are 5,227 problems on Cody, so William has solved over 95%. The next competitor is over 500 problems behind. His score is also clearly the highest, approaching 60,000.
Please take a moment to congratulate @William.
goc3
goc3
最後のアクティビティ: 2024 年 6 月 7 日

There are a host of problems on Cody that require manipulation of the digits of a number. Examples include summing the digits of a number, separating the number into its powers, and adding very large numbers together.
If you haven't come across this trick yet, you might want to write it down (or save it electronically):
digits = num2str(4207) - '0'
That code results in the following:
digits =
4 2 0 7
Now, summing the digits of the number is easy:
sum(digits)
ans =
13
goc3
goc3
最後のアクティビティ: 2023 年 11 月 6 日

Have you ever learned that something you were doing manually in MATLAB was already possible using a built-in feature? Have you ever written a function only to later realize (or be told) that a built-in function already did what you needed?
Two such moments come to mind for me.
1. Did you realize that you can set conditional breakpoints? Neither did I, until someone showed me that feature. To do that, open or create a file in the editor, right click on a line number for any line that contains code, and select Set Conditional Breakpoint... This will bring up a dialog wherein you can type any logical condition for which execution should be paused. Before I learned about this, I would manually insert if-statements during debugging. Then, after fixing each bug, I would have to delete those statements. This built-in feature is so much better.
2. Have you ever needed to plot horizontal or vertical lines in a plot? For the longest time, I would manually code such lines. Then, I learned about xline() and yline(). Not only is less code required, these lines automatically span the entire axes while zooming, panning, or adjusting axis limits!
Share your own Aha! moments below. This will help everyone learn about MATLAB functionality that may not be obvious or front and center.
(Note: While File Exchange contains many great contributions, the intent of this thread is to focus on built-in MATLAB functionality.)