# Assigning a variable to any value in a matrix

22 vues (au cours des 30 derniers jours)
roram le 27 Avr 2016
Commenté : dpb le 27 Avr 2016
Hi,
I am having trouble on a project involving matrices.
An example with simplified but similar code:
Matrix = [0 1 4; 4 1 3];
for x = 1:10
if x + y == 5
My goal is to have y be ANY value in the original matrix, so the if statement is true if x + ANY Matrix Value is equal to 5.
Is this possible without using an extra for loop?
Thanks!
##### 0 commentairesAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens

Connectez-vous pour commenter.

### Réponses (3)

Star Strider le 27 Avr 2016
Modifié(e) : Star Strider le 27 Avr 2016
You came close to answering it yourself. There is an any funciton.
Experiment with this to see if it does what you want:
Matrix = [0 1 4; 4 1 3];
y = Matrix;
for x = 1:10;
logic = any(x + y == 5)
end
EDIT To see the results of the comparison for different values of ‘x’, tweak the code to store the values, and display them in an array:
Matrix = [0 1 4; 4 1 3];
y = Matrix;
for x = 1:10;
logic(x) = nnz(any(x + y == 5));
end
Result = [[1:10]', (logic > 0)']
Result =
1 1
2 1
3 0
4 1
5 1
6 0
7 0
8 0
9 0
10 0
##### 0 commentairesAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens

Connectez-vous pour commenter.

Jon le 27 Avr 2016
Try this
for x = 1:10
if sum(x + Matrix(:) == 5) > 0
disp(x)
end
end
##### 2 commentairesAfficher 1 commentaire plus ancienMasquer 1 commentaire plus ancien
dpb le 27 Avr 2016
There are multiple possible locations...but, use logical array or find or the like--
>> x=1; % define an example x
>> (x+Matrix==5) % logical array
ans =
0 0 1
1 0 0
>> [i j]=find(x+Matrix==5); % return locations
>> disp([i j])
2 1
1 3
>>
Again, need more detail on what your end result is to be to have any real definitive implementation suggestions.

Connectez-vous pour commenter.

dpb le 27 Avr 2016
Matrix = [0 1 4; 4 1 3];
for x = 1:10
if any(x+Matrix(:)==5)
...
NB: use of : to treat array as a vector such that any will return a single result.
You could possibly eliminate the loop entirely depending on what the resulting operation is.
##### 0 commentairesAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!