- "I have a excel file which has 7 colums" - it has only 6 columns
- "The second column as 1 value" - not clear
- "I want to multiply the values of column 5 and column 6 and add them" Multiply - OK, "and then add them - what exactly to add to the multiplication result?
HOW TO ADD ONE COLUMN BASED ON ANOTHER COLUMN
6 views (last 30 days)
Show older comments
Tanmoyee Bhattacharya
on 30 Jun 2024
Edited: Tanmoyee Bhattacharya
on 4 Jul 2024
I have a file containing some columns.
hru sub year mon area gw_rchrg
1 1 2016 1 61 1.87
2 1 2016 1 233 2.91
3 1 2016 1 345 5.45
4 1 2016 1 600 1.23
5 1 2016 1 400 2.67
6 1 2016 1 235 1.34
7 2 2016 1 123 3.67
8 2 2016 1 178 4.78
9 2 2016 1 345 1.56
10 2 2016 1 430 2.67
11 2 2016 1 250 1.12
12 2 2016 1 278 2.12
I have a excel file which has 7 colums. In colum 2 there are rows containing 1 and 2. I want to do some operations.
The second column as 1 value. I want to multiply the values of column 5 and column 6 and add them according to 1 value if column 2. Similarly do it for 2 values of column 2. If there is any code for this?
0 Comments
Accepted Answer
Matlab Pro
on 30 Jun 2024
You need to write more clearer with less errors;
You wrote
Anyhow , here is a simple example that might help you:
data = readtable('HRU.xlsx');
idx = data.SUB == 1;
mult = data.AREAkm2 .* data.GW_RCHGmm;
mult(~idx) = nan; % Make all values where "SUB ~=1" : NaN
data.('new_column') = mult;
Good luck
3 Comments
Matlab Pro
on 3 Jul 2024
Moved: Voss
on 3 Jul 2024
Hi again @Tanmoyee Bhattacharya
Do you mean you want to create a new column for each unique value in Column #2?
If so- here is a possible solution. I have timed it. it take no time to create 60 new columns based on 60 unique values in colunmn #2:
function tanmoyee_code()
data = readtable('HRU.xlsx');
% Creating logical indexes per value of the 'SUB' column (#2)
un_subs = unique(data.SUB);
idxes = arrayfun(@(x) data.SUB==x, un_subs, 'UniformOutput', false);
fld_names = strsplit(sprintf('sub_%d~',un_subs),'~');
fld_names(cellfun(@isempty ,fld_names)) = []; % chop empty entries
mult = data.AREAkm2 .* data.GW_RCHGmm;
tic
for iFld = 1:length(fld_names)
fld1 = fld_names{iFld};
tmp = mult;
tmp(~idxes{iFld}) = nan;
data.(fld1) = tmp;
end
toc
More Answers (0)
See Also
Categories
Find more on Logical 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!