Extract values from matrix using symbolic function

I am coding a live function, of which a matrix B is the input. I am trying to define a symbolic function b(a,c) which extracts the (a,c)th entry of the matrix B, B(a,c). As such my code is as follows (please note that this is the very first part of my live function)
syms a c
assume(a, "integer")
assume(c, "integer")
syms b(a,c)
b(a,c) = B(a,c);
However, when I try to run it, I get the error "Error using indexing Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments must be symbolic variables, and function body must be sym expression."
Why does this happen and how do I fix it?

3 Comments

To use a and c (or any other variables) as indices, you need to define them as numeric (or logical) values (which is what the MATLAB indexing stated in the error message is).
Symbolic variables are not accepted as indices.
so how can I define a function which extracts the entries of a matrix?
You can want to do something. But that does not mean it is possible. Language syntax is what it is, and you cannot arbitrarily define what you want and assume it will work. A symbolic variable cannot be used as an index.
But there seems to be no reason to have defined a and c as symbolic. Just because you don't currently know the value of a variable, does not mean it MUST be symbolic. For example, you can define a function handle.
extrct = @(B,a,c) B(a,c);
B = magic(5)
B = 5x5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
extrct(B,2,3)
ans = 7
Honestly though, I'm not sure I see that as any improvement over the simpler direct indexing:
B(2,3)
ans = 7

Sign in to comment.

Answers (0)

Products

Release

R2023b

Asked:

on 4 Mar 2024

Edited:

on 4 Mar 2024

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!