Chain array indexing error to access elements of a function
93 views (last 30 days)
Show older comments
I keep getting an error in trying to access elements of an array that is defined as a function. Consider the foloowing function that demonstrates my issue:
test = @(t) [t, t^2];
which takes in the time parameter, t, and returns a 1x2 array of floats that depend on that value of t. Now, I want to define a function, x = @(t) to be the first element of the 1x2 array returned by test(t).
How can I do this? I have tried the following:
x = @(t) test(t)(1). However, this doesn't work. Specifically, Matlab considers (t)(1) to be a nested index, which is strictly not allowed. The error message returned by Matlab is "Invalid array indexing or function call. Chaining outputs after parenthesis is not supported".
How can I achieve what I described?
Note that test is an example function, my actual function is a little more involved.
EDIT (Additional info based on answers)
Based on answer I received, it is worth clarifying that I do not have access to the function x(t). I.e. I am working with vectors that define the solution, which in our above example would read
test = @(t) [ x(t), y(t), z(t) ] % This step is yielding after some pre-calculation that bears no signifcance to the question
The rest of the calculation requires knowledge of just x(t) and z(t), so I would like to define these functions by accessing elements of test.
1 Comment
Steven Lord
on 26 Apr 2023
which takes in the time parameter, t, and returns a 1x2 array of floats that depend on that value of t.
It does that under certain circumstances. In general it returns an array with the same size as t except in dimension 2, where the size is twice as large as t's size in dimension 2.
test = @(t) [t, t^2];
t = magic(4)
result = test(t)
[size(t); size(result)]
So would you really want the second element of the output or the second half of the output?
Answers (2)
VBBV
on 26 Apr 2023
Edited: VBBV
on 26 Apr 2023
test = @(t) [t, t^2]
% test using t = 10
y = test(10);
% define e.g function
x = @(t) t.^2+2*t
% get the value of function using first value returned by test
x(y(1))
chicken vector
on 26 Apr 2023
The fact that you can't concatenate indexing is a well-known Matlab limitation whose implementation has already been suggested on the forum.
The best option that you have is to use:
x = @(t) t
By doing so you are also saving computational time because you want to compute test to only access the first element is a waste of resources.
2 Comments
chicken vector
on 26 Apr 2023
This might be too intricate for your needs but it works:
test = @(t) [t,t^2];
x = @(t) extractFirstTestValue(test,t);
function firstValue = extractFirstTestValue(test,t)
testValue = test(t);
firstValue = testValue(1);
end
See Also
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!