loop through cell arrays and perform calculations using rows from another cell array
8 views (last 30 days)
Show older comments
I am trying to do some calculations on some data which are stored in cell arrays but I cannot work around it.
I have a 1xm cell array named (DATA) which consists of kxn tables and a second cell array 1xm consisting of 1xn tables named (To).
I want to loop through the first cell array and perform the following equation on each row of each column of K and return a new cell array.
new_data = (Data - To)/To;
I am doing the following but no luck.
for j = 1:size (Data,2)
file = Data {1,j};
A_Data= table2array(file(:,2:31));
[NEW_TABLE{j}]= ((A_Data(1,j) - (To(1,j))./(To(1,j));
end
4 Comments
Answers (1)
dpb
on 8 Mar 2021
Edited: dpb
on 8 Mar 2021
DATA={table(rand(4,3))}; DATA(2,1)={table(rand(4,3))};
To={table(randi(5,4,1))}; To(2,1)={table(randi(5,4,1))};
% preliminaries of some sample data to work on out of the way, ...
% the engine
N=cellfun(@(d,t) (d{:,:}-t{:,:})./t{:,:},DATA,To,'UniformOutput',false);
yields
>> N{1}
ans =
-0.8177 -0.8075 -0.8770
-0.8086 -0.7553 -0.9355
-0.8487 -0.9777 -0.9926
-0.1567 -0.6039 -0.0256
>> DATA{1}
ans =
4×1 table
Var1
_______________________________
0.72902 0.77016 0.49206
0.76565 0.97866 0.25809
0.75658 0.11136 0.036966
0.84327 0.39608 0.97438
>> (DATA{1}.Var1-To{1}.Var1)./To{1}.Var1
ans =
-0.8177 -0.8075 -0.8770
-0.8086 -0.7553 -0.9355
-0.8487 -0.9777 -0.9926
-0.1567 -0.6039 -0.0256
>>
one could wrap N into a table if really wanted...
Also NB: that the anonymous function could have used .Var1 notation as well instead of {} syntax; the latter works whether is on variable as an array or a set of variables as columns...
NB2: The missing "." in the element-wise division using "./" is at least one source of your problem altho I didn't try to read the code itself for accuracy otherwise.
4 Comments
dpb
on 10 Mar 2021
ADDENDUM:
One could write code to find the intersection of the variables between the two by name from the Properties.VariableNames cell arrays and operate only over those -- but it may/may not match in size depending upon what the two tables contain -- in this case, one could get all of the data table and throw away the extraneous T column, if the names don't match 1:1, there could be anything from that to the null set.
Siddharth Bhutiya
on 30 Mar 2023
In 23a tables and timetables support standard arithmetic operations so in the cellfun call above you would no longer need the brace indexing (d{:,:}). It can be simplified to something like below.
DATA = {table(rand(4,3))}; DATA(2,1)={table(rand(4,3))};
To = {table(randi(5,4,1))}; To(2,1)={table(randi(5,4,1))};
N = cellfun(@(d,t) (d-t)./t, DATA, To, UniformOutput=false)
N{1}
It will also keep the output as a table.
See Also
Categories
Find more on Tables 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!