How do can I check whether 2 columns in an array have equal values in a row?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Robert
2016-5-2
编辑:Robert
2016-5-2
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 个评论
Robert
2016-5-4
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.
更多回答(1 个)
Walter Roberson
2016-5-2
mask = positions(:,1) == positions(:,5);
SimIDs = ones(size(mask));
SimIds(mask) = positions(mask,1) + 1;
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!