working with numbers in the array names in for/ if loop

Hi
I am struggling with a program in matlab where I need to make arrays with numbers varying in their name in the loop itself:
For example: given dataset with columns: data_column_1, data_column_2, data_column_3 . . . upto 10
Lets say:
………………………….
For i=1:10
array_(i)= mean(data_column_(i) w.r.t data_column_1 ) %( for all 10 arrays )
end
………………………………..
Solution must be like
array_1 has mean of data in data_column_1 wrt data_column_1
array_2 has mean of data in data_column_2 wrt data_column_1
array_3 has mean of data in data_column_3 wrt data_column_1 and so on.
I will really appreciate some solution here. Thanks

Answers (1)

Dynamically naming variables is not a good coding practice.
As you have numbers only, you should concatenate all the data in a numerical array and directly use mean with the specific dimension.

5 Comments

Can you show how? Through an example?
How do you get the arrays data_column_1, data_column_2, ... data_column_n?
Are they obtained as output from a code? If so, could you share the code?
The basic idea is -
%I assume the arrays are a row vector
data_column = vertcat(data_column_1, data_column_2, .., data_column_n);
out = mean(data,2)
If the arrays are a column vector, then use horzcat and use 1 instead of 2 for mean.
If you can provide more information about the questions I asked above, we might be able to optimize the code further.
Heres the code. My dataset(arr) has 3 columns, I need to find mean of all columns for the unique values of column 1. then plot those averages wrt to unique values i.e plot(col1,col2), plot(col1,col3). In my prog, I am getting Multiple values of c(nx3 matrix), which is a variable to store the unique mean values for each iteration. I have 10 bins. And I get different c-values for each iteration. It gives me error that size of arrays are not same on both sides. so program is stuck here. I will appreciate ome help, if you can.Thanks
.......................................................
for i= 1:10
if isempty( arr) )==0
for j=1:3
c(:,j)=splitapply(@mean,arr(:,j),findgroups(arr(:,1))); %<----------- error line.
end
c
plot(log(c(:,2)),c(:,1),'b.')
hold on
end
end
From what I understood by the description you gave, try this -
(I didn't understand the bit about the 10 bins.)
idx = findgroups(arr(:,1));
u = unique(idx);
c = zeros(numel(u),3);
for j=1:3
c(:,j)=splitapply(@mean,arr(:,j),idx);
end
figure
plot(c(:,1), c(:,2), 'b.')
hold on
plot(c(:,1), c(:,3), 'r.')
If this does not work, please attach the data for "arr".

Sign in to comment.

Asked:

on 22 Oct 2023

Commented:

on 26 Oct 2023

Community Treasure Hunt

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

Start Hunting!