How to check if a matrix has a certain variable?

5 views (last 30 days)
Say I have matrix X:
X = [ 1 , 4, 2]
where
X(1) = 1
X(2) = 4
X(3) = 2
and matrix A with:
A(1) = X(1) + X(2)
A(2) = X(2) + X(3)
A(3) = X(1) + X(3)
I made a nested for loop j from 1 to 3 and k from 1 to 3 to make a 3x3 matrix as my output as matrix W
W = zeros(3,3)
for j = 1:3
for k = 1:3
if (don't know what to put here)
W(j,k) = A(j) + 100
else
W(j,k) = A(j)
end
W(j,k) = A(j)
end
end
j is for each row corresponding to A
k is for each column corresponding to X
In each element of the matrix,I want to check each A(j) in the matrix if it has X(k) in its equation then if true I would add the value 100 to that A(j) that was true.
And if that A(j) did not contain X(k) in its equation then nothing would be added to A(j).
Then I would insert the new value to replace the old element in the matrix
For example, if if the nested for loop goes to W(1,2) then it would check if X(2) is in A(1).
Since true then new W(1,2) would be A(1)+100
My problem is that I don't know how to code to check for each X(k) in A(j)
How do I check A(j) for X(k) as a variable?

Accepted Answer

Walter Roberson
Walter Roberson on 29 Feb 2020
Rewrite A as
M = [1 1 0;
0 1 1;
1 0 1];
A = M * X';
Now you can test if A(j) uses X(k) by testing whether M(j, k) is nonzero.

More Answers (2)

David Hill
David Hill on 29 Feb 2020
How about?
if mod(j-k,3)==2||j==k

Walter Roberson
Walter Roberson on 29 Feb 2020
Edited: Walter Roberson on 29 Feb 2020
As you do not seem to feel that my earlier answer works for your situation:
It is not possible to do what you want to do. As soon as a variable is assigned to, matlab discards all information about how the value was calculated. It is, for example, not possible to tell whether an A value was calculated as X(2) or as 2*X(3): all you get is the final value.
If you were to use the symbolic toolbox then you could make A a matrix of symbolic expressions, which you could ude symvar() on to determine whether a particular symbolic variable was involved.
However, a symbolic expression cannot be simultaneously an expression and the value the expression evaluates to when you substitute in particular numeric values. You cannot look at symbolic 4 as a result and ask whether it was X(2) substituted with X(2)=4, versus 2*X(3) substituted with X(3)=2.
In my previous Answer I showed how to formulate the calculation of your A in such a way that you could probe which variables were involved by examining a numeric matrix. However there is no way, and there will never be a way, to look at the numeric A and be able to ask which variables were used to calculate it.

Categories

Find more on Creating and Concatenating Matrices 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!