Effacer les filtres
Effacer les filtres

Creating a logic vector out of 2D matrix

2 vues (au cours des 30 derniers jours)
Lama Hamadeh
Lama Hamadeh le 27 Avr 2022
Commenté : Jon le 27 Avr 2022
Hi,
How can I create a logic vector v out of a matrix M in a way that each row of v equals to 1 when the second element of Mper row equals to 0, as illustrated below:
My attempt in coding this is as following:
%M matrix
M = [1 2;
2 0;
3 1;
4 0;
5 3;
6 0;
7 2;
8 4;
9 0;
10 1];
%initialise v vector
v = [];
%create v vector
for i =1:size(M,1)
if M(i,i) == M(i,0)
v(i) = 1;
else
v(i) = 0;
end
end
An error message of "Index in position 2 is invalid. Array indices must be positive integers or logical values." apears.
Any help would be appreicted.
Thanks.

Réponses (3)

Dyuman Joshi
Dyuman Joshi le 27 Avr 2022
Indexing in MATLAB starts with 1 and not 0.
M = [1 2;
2 0;
3 1;
4 0;
5 3;
6 0;
7 2;
8 4;
9 0;
10 1];
%initialise v vector
v = [];
%create v vector
for i =1:size(M,1)
if M(i,2) == 0 %Comparing 2nd element of ith row to 0 as you mentioned
v(i,1) = 1;
else
v(i,1) = 0;
end
end
v
v = 10×1
0 1 0 1 0 1 0 0 1 0

Fangjun Jiang
Fangjun Jiang le 27 Avr 2022
Modifié(e) : Fangjun Jiang le 27 Avr 2022
M(i,i) == M(i,0)
should be
M(i,2) == 0
When you have this type of error on a very simple script, put a break point and run the script line by line. You will be able to debug the problem by yourself.

Jon
Jon le 27 Avr 2022
%M matrix
M = [1 2;
2 0;
3 1;
4 0;
5 3;
6 0;
7 2;
8 4;
9 0;
10 1];
% logic vector
v = ~M(:,2)
  1 commentaire
Jon
Jon le 27 Avr 2022
The above uses the fact that MATLAB treats double values which are zero as if they were logical false. You could also do what you want, maybe more clearly using
v = M(:,2)==0

Connectez-vous pour commenter.

Catégories

En savoir plus sur Resizing and Reshaping Matrices 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!

Translated by