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!