Hello everyone,
I am using the symbolic toolbox to create symbolic matrices, then I need to evaluate the value of each members of the matrix.
So, here is what I have done so far.
clear;
clc;
A = sym('A', [2, 3], 'real')
for i = 1:2
for j = 1:3
A(i, j) = i*j;
z = str2sym ( strcat('A', num2str(i), '_', num2str(j) ) )
end
end
Then, I obtain:
>> A
A =
[ 1, 2, 3]
[ 2, 4, 6]
However, when I want to get the member value, e.g: A1_3, I got the error "Unrecognized function or variable 'A1_3'."
That's why I created a string and conver to a symbolic value, and store in z. But I don't know how to get my Ai_j = A(i, j).
My goal is that each member Ai_j of the symbolic matrix gets the value of A(i, j). Can anyone help me with this ?
Thanks in advance.

 採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 16 日

1 投票

Why do you want to create variable names like A1_3, A2_3, etc., when you can directly index the matrix A. Creating a separate variable name for each element is not an efficient coding approach: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval.
Also, MATLAB does not provide a good way of doing what you want to do.

5 件のコメント

AMEHRI WALID
AMEHRI WALID 2020 年 11 月 16 日
Actually, I want to avoid directly indexing the matrix A because its size changes every time in my application, I only showed an example in my question, ot know if it is possible to perform something like this
Ameer Hamza
Ameer Hamza 2020 年 11 月 16 日
I believe there must be a way to use array in your case. But If you must want to do it in this way, then read about eval().
clear;
clc;
for i = 1:2
for j = 1:3
var_name = sprintf('A%d_%d', i, j);
eval([var_name '=i*j']);
end
end
It will create 6 symbolic variables.
AMEHRI WALID
AMEHRI WALID 2020 年 11 月 16 日
編集済み: AMEHRI WALID 2020 年 11 月 16 日
Great, this is exactly what I was looking for.
Thank you very much!
Ameer Hamza
Ameer Hamza 2020 年 11 月 16 日
I am glad to be of help!
Steven Lord
Steven Lord 2020 年 11 月 16 日
Actually, I want to avoid directly indexing the matrix A because its size changes every time in my application
That's no problem. Use size or numel to avoid having to hard-code the size of the matrix.
function showAllElements(A)
fprintf("Input argument A is of size [" + num2str(size(A)) + "]." + newline);
for whichElement = 1:numel(A)
fprintf("Element " + whichElement + " of A is %g.\n", A(whichElement));
end
Call this as:
showAllElements(magic(4))
showAllElements(rand(3, 5))

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2020 年 11 月 16 日

コメント済み:

2020 年 11 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by