Matlab中括号在函数输出参数捕获中的用法疑问
~ Placeholder Hey there! Let's clear up your confusion around MATLAB's bracket syntax for handling function outputs—this is a super common question when you're learning to work with functions that return multiple values.
1. What does [~,data]=prices_init; mean?
The ~ in MATLAB is a placeholder for output arguments you don't want to store. Here's the breakdown:
- The function
prices_initis designed to return two separate output values. - The first output is something you don't need, so you use
~to tell MATLAB to ignore it instead of assigning it to a named variable. - The second output is assigned to the variable
data, which you can then use later in your code.
Think of it like saying: "Run prices_init, throw away the first result, and save the second one as data."
2. How to capture output arguments from functions like union(A,B)
Let's use the union example from the MATLAB docs: [C,iA,iB] = union(A,B). This function returns three outputs, in order:
C: The sorted union of elements fromAandBiA: Indices showing where each element ofCappears first inA(0 if the element isn't inA)iB: Indices showing where each element ofCappears first inB(0 if the element isn't inB)
Here's how you can capture these outputs in practice:
Case 1: Capture all three outputs
If you need every result, assign each to a named variable in the same order as the function's output:
A = [1, 3, 5]; B = [2, 3, 4]; [my_union, indices_in_A, indices_in_B] = union(A, B);
After running this:
my_unionwill be[1, 2, 3, 4, 5]indices_in_Awill be[1, 0, 2, 0, 3]indices_in_Bwill be[0, 1, 2, 3, 0]
Case 2: Capture only specific outputs
If you don't need all outputs, use ~ to skip the ones you don't want:
- To get only the union (
C) and indices inA(iA):[my_union, indices_in_A, ~] = union(A, B); - To get only the indices in
B(iB):[~, ~, indices_in_B] = union(A, B); - If you only need the first output (
C), you can even skip the brackets entirely:my_union = union(A, B);
Key Rules to Remember
- Use square brackets
[]to capture multiple output arguments. - Variable names inside the brackets must match the order of the function's declared outputs.
- Use
~as a placeholder to ignore any output you don't want to store. - You can omit trailing outputs without using
~(e.g.,[C,iA] = union(A,B)works if you don't neediB).
内容的提问来源于stack exchange,提问作者swedishfished

