Compare two data in a column of matrix

5 ビュー (過去 30 日間)
Kim Lopez
Kim Lopez 2017 年 10 月 27 日
回答済み: BhaTTa 2024 年 10 月 23 日
Suppose i have a table with the following data below. Column C should be compared to column A. In the table, since -150 in column C is less than 0 in column A, then column D would copy the value of column B which is 2. The same with -50, since it is less than 0, then column D will have a value of 2. How can i implement this? Any help is appreciated.
A B C D
0 2 -150
100 3 -50
150 5 0
200 6 50
250 8 100
300 11 300
The result would something look like this
A B C D
0 2 -150 2
100 3 -50 2
150 5 0 2
200 6 50 3
250 8 100 3
300 11 300 11
  1 件のコメント
Chandra Sekhar Mattupalli
Chandra Sekhar Mattupalli 2017 年 10 月 27 日
All the rows in column C needs to be compared with first row element of Column A?

サインインしてコメントする。

回答 (1 件)

BhaTTa
BhaTTa 2024 年 10 月 23 日
Hey @Kim Lopez, you can use logical indexing to compare the values and assign them, below i have provided the code implementing the same:
% Sample data
A = [0; 10; 20];
B = [2; 4; 6];
C = [-150; -50; 25];
% Initialize D with NaN or some other placeholder
D = NaN(size(C));
% Apply the logic: if C is less than A, then D gets the value of B
D(C < A) = B(C < A);
% Display the results
result = table(A, B, C, D)
result = 3x4 table
A B C D __ _ ____ ___ 0 2 -150 2 10 4 -50 4 20 6 25 NaN
Hope it helps.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by