Reputation: 1
I was wondering how can I call a variable within a table that I have created?
For instance, lets say I have a table with these variables:
Width 3 4.5 5 6.7
Length 4.6 5.7 5.7 5.6
Type 1 1 3 4
How do I ask Matlab to retrieve all numbers that are equal to 1 from Type variable? Here's what I am trying to do:
A=[]; %Create empty matrix
for i=1:numel(Type) %for every number within the variable
if Type(i) == '1'; %if it equals to 1
A(i)= Type(1) %append to matrix
end
end
Upvotes: 0
Views: 73
Reputation: 3313
You need use what's called "logical Indexing" -
Let's say you have a variable tbl
:
>>tbl= [110 1; 120 2; 13 3;140 1]
tbl =
110 1
120 2
13 3
140 1
We want to get all entries where the second column is == 1. We can create a similar sized array, where there is an entry for each row of tbl
, where it's false
if ~=1, or true
if it's ==:
>>index = tbl(:, 2)==1
index =
1
0
0
1
Note the use of the :
operator - that says "use all elements" - in this case, all rows. Now, you just apply that to tbl itself:
>> crabs = tbl(index, 1)
crabs =
110
140
Now, you can make that a one-liner:
>> crabs = tbl(tbl(:, 2)==1, 1)
Upvotes: 2