Tony YEe
Tony YEe

Reputation: 235

Create mean of each column and put it into the workspace

Below is my matlab code:

  for t=1:5
    data=[1 3 5 7 9;2 4 6 8 10];
    k(t)=mean(data(:,t));
    end

As a result,k(1)=1.5,k(2)=3.5, ... ,k(5)=9.5. I want to create a result which combine all of them as shown in below:

Result=[1.5;3.5;5.5;7.5;9.5]

Any good idea to do that??Thanks.

Upvotes: 0

Views: 81

Answers (2)

KatyB
KatyB

Reputation: 3980

data=[1 3 5 7 9;2 4 6 8 10];
R = mean(data)';

Amended:

As was mentioned above, if this solution is not what you expected, I'm not really sure what your asking. From your title you mention 'put into the workspace'? Does this mean you want a variable for each value in 'R'? If so, try:

for i = 1:5    
    kk = R(i);
    % eval(sprintf('k%d = kk', i)); % better to avoid eval use assignin instead
    assignin('base',['K' sprintf('%d',i)],kk);
end

Upvotes: 2

mythealias
mythealias

Reputation: 350

You can just use,

data = [1 3 5 7 9; 2 4 6 8 10];
k = mean( data );        % k = [1.5, 3.5, 5.5, 7.5, 9.5];
% To get a column vector use:
k = mean( data )';       % k = [1.5; 3.5; 5.5; 7.5; 9.5];

Check the documentation of mean for more details.

Upvotes: 2

Related Questions