How do can I check whether 2 columns in an array have equal values in a row?
2 views (last 30 days)
Show older comments
I have an array of 5 columns and I would like to check whether columns 1 and 5 have the same value (1) and report the result to a vector. If the values are not the same, I want the vector to have values of 1 (e.g. [1, 1, 1, 1, 1, 1]). If the values in columns 1 and 5 are the same for a given row, I want to increase the value by 1 (e.g. 1, 1, 1, 1, 2, 2).
I receive the following error: Operands to the and && operators must be convertible to logical scalar values. When I change the && to &, the function returns ans = []. In the code below, the array is named positions and the vector into which I would like the values reported is named SimIDs.
Please let me know any additional information I can provide.
i=1;
SimIDs=[];
if positions(:,1)==1 && positions(:,5)==1
i=i+1;
SimIDs=[SimIDs,i];
end
0 Comments
Accepted Answer
Robert
on 2 May 2016
Edited: Robert
on 2 May 2016
Your if statement is examining the entire column because you use : in your indexing expression instead of a loop index, but you increment i as though you were in a loop.
Instead, try using cumsum on your logical result as follows
SimIDs = cumsum(positions(:,1)==1 & positions(:,5)==1) + 1;
% add one to start at one rather than zero
2 Comments
Robert
on 4 May 2016
Yes, if the first value will always be 1, not zero, then your SimIDs will never start at zero anyhow. You don't need the +1.
More Answers (1)
Walter Roberson
on 2 May 2016
mask = positions(:,1) == positions(:,5);
SimIDs = ones(size(mask));
SimIds(mask) = positions(mask,1) + 1;
0 Comments
See Also
Categories
Find more on Data Types 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!