find a value & store in new variable (again)
8 次查看(过去 30 天)
显示 更早的评论
Dear Matlab friends,
We recently posted a question about finding values and storing them in new variables:
Our question remains in the sense that we would like to know how to procede when we have a matrix rathen than a cell array.
Indeed, we have a 384 x 14 matrix A, and we would like to find all occurrences of number [2] in column 1, and save corresponded value in column 2 in a new variable "new_variable":
A =
3 5 6 ...
2 3 5
2 3 4
1 4 5
5 7 9
...
so the result would be:
new_variable =
2
2
The suggestion for cell arrays was
new_variable = A{2}(A{1} == 2);
We thank you very much for any suggestion!
Best,
Udiubu
0 个评论
回答(3 个)
Geoff
2012-3-19
Use logical indexing:
new_variable = A(A(:,1)==2, 2);
This indexes all those rows of A where column 1 is equal to 2, selects column 2 and assigns the result to new_variable.
Geoff
2012-3-19
Okay, since your matrix actually contains cells the equality operator doesn't work. I'll split the code up for extra clarity, since another reader insists ;-)
I'm still not sure if you want to replace column 2 with the value 2 or just copy the filtered column 2 into new_variable... The question was confusing. Anyway,
I would do this:
rowidx = cellfun( @(x) x==2, A(:,1) );
new_variable = cell2mat(A(rowidx,2));
cellfun maps a function over all elements of a cell-array or matrix. The '@(x) x==2' part is an anonymous (on-the-fly/adhoc) function. Here we use it on the first column. The output is a vector of booleans, which we then use as a logical index.
Edit:
The other way is to just extract the numeric columns that are of interest and use my other solution that works on matrices:
B = cell2mat(A(:,1:2));
new_variable = B( B(:,1)==2, 2);
6 个评论
Geoff
2012-3-19
That's odd. Did you use my edited version of the first code segment? Using A{rowidx,2} was incorrect.
I assume your matrix is generally numeric (ie the numbers themselves are not strings), but those NaNs get in the way. You could try converting them to numbers too:
A{cellfun(@(x) strcmpi(x,'nan'), A)} = NaN;
Aldin
2012-3-19
Here, try this code:
A = [ 2 1 3 2 4; 4 5 3 6 2; 2 3 5 3 6; 1 2 5 3 6; 3 2 5 2 5]
for i = 1:5
if A(i,1) == 2
A(i,2) = 2;
end
end
4 个评论
Aldin
2012-3-19
oooo i know what you want :)
A = [ 2 1 3 2 4; 4 5 3 6 2; 2 3 5 3 6; 1 2 5 3 6; 3 2 5 2 5];
counter = 0;
for i = 1:5
if A(i,1) == 2
counter = counter + 1;
new_variable(count) = A(i,2);
end
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!