How to separate rows from an array
7 次查看(过去 30 天)
显示 更早的评论
Hey guys,
I am fairly new to MatLab and I am trying to figure out how to seperate out certain rows from my main array into a new array based on the contents of my first column.
For Example
column 1 column 2 column 3
1 Cash 5.00
2 Credit 10.00
3 Debt 1.50
So lets say I wanted to separate out cash and credit and add them to a new array so I can ultimately sum the contents of column 3 together.
Something along the lines of "if column 1 is => 0 & =<2, move whole rows to " array 2"
Thanks for your help.
回答(3 个)
Fangjun Jiang
2011-10-27
If you matrix is numerical, it is actually easy.
a=[1 5.00
2 10.00
3 1.50
1 5.00
2 10.00
3 1.50];
index=a(:,1)>0 & a(:,1)<3;
b=a(index,:)
12 个评论
Fangjun Jiang
2011-10-27
What are you talking about? Run the xlsread() and your data will be put in the 'a' variable. The code above is just an example showing how it works on a cell array.
Honglei Chen
2011-10-27
Here is a simple example:
>> x = rand(3,3)
x =
0.9055 0.6581 0.2495
0.2045 0.1836 0.3782
0.9654 0.3151 0.5356
>> y = x(x(:,1)>0.5,2)
y =
0.6581
0.3151
HTH
0 个评论
Alex
2011-10-28
Here's an example using the text 'credit' and 'cash' to find and sort out what you want easily.
col_2 = {'credit' 'credit' 'cash' 'cash'};
col_3 = [ 1 2 3 4 ];
%find the credit rows
credit_rows = strcmp(col_2,'credit');
%find indexes of credit row
credit_index = find(credit_rows == 1);
%now we have the index of each credit value, so we can sum these, or move them
only_credit_col = col_3(credit_index);
total_credit = sum(only_credit_col);
%remove the credit cells from the original column - this will leave you a column with only cash values
col_3(credit_index) = [];
cash_col = col_3;
cash_tot = sum(cash_col);
results: credit_col = [1 2] total_credit = 3
cash_col = [3 4] total_cash = 7 total_cash = 7
1 个评论
Fangjun Jiang
2011-10-28
credit_rows is a logic array. It can be used for index. You don't need to generate the credit_index using find()
col_2 = {'credit' 'credit' 'cash' 'cash'};
col_3 = [ 1 2 3 4];
%find the credit rows
credit_rows = strcmp(col_2,'credit');
%now we have the index of each credit value, so we can sum these, or move them
only_credit_col = col_3(credit_rows);
total_credit = sum(only_credit_col);
%remove the credit cells from the original column - this will leave you a column with only cash values
col_3(credit_rows) = [];
cash_col = col_3;
cash_tot = sum(cash_col);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!