Adding values of Columns in a matrix to create another matrix (for loop)

I have a 442x25 matrix 'yield' which I want to sum each column in 'yield' to create a 1x25 matrix 'nyi', so this can be multiplied by another 1x25 matrix Np.
I ran this exact code earlier on a different computer where both of the matrices were produced the size they are meant to be so i am not sure what is wrong.
It seems as if the code thinks there are only two columns.? But I have 25 columns
I am an amateur when it comes to matlab so I would really appreciate any help!
See the code for my loop and errors produced:
dim=size(E_min,2);
fun = @(E) A*exp(-E/kT);
for i = 1:dim
Np=integral(fun,E_min(i), E_max(i));
Np(i)=Np;
y=yield(:,1:i,1);
nyi=sum(y);
num(:,i)=nyi*Np(i);
end
The code is recognising my dim as 1x25 (which is correct) however when I run the following loop I am getting an error
Unable to perform assignment because the size of the left side is 1-by-1 and
the size of the right side is 1-by-2
Error in matrixfunction (line 41)
num(:,i)=nyi*Np(i);

 Accepted Answer

dim=size(E_min,2);
% dim = 25
fun = @(E) A*exp(-E/kT);
Np = [];
nyi = [];
for i = 1:dim
Np(i)=integral(fun,E_min(i), E_max(i));
% size(Np) is 1x25
% size(yield) is 442 x 25
y=yield(:,i); % size(y) is 442 x 1
nyi(i)=sum(y); % size(nyi) is 1x25
end
num = nyi .* Np; % size(num) is 1x25
Hope this helps!

6 Comments

I have tried this and the same thing is being produced.
It seems to be treating i as 1 and not as a loop?
Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 442-by-1.
Error in matrixfunction (line 41)
num(:,i)=nyi*Np(i);
I have 2 (1x25) matrices names E_min and E_max, I am integrating with boundaries E_min(1) and E_max(1), then E_min(2) and so on to create a matrix of 1x25 for Np. It is instead giving me a 1x1 value.
I want Np to be a matrix 1x25, how can I do this? so that i get the integrated values for each E_min E_max in one row
I also want yield to be a matrix of 442x25, where each column is then sum to give a 1x25 matrix (nyi)
Num is then just multiplying the values of Np(if Np were a 1x25) and nyi(if it were a 1x25 matrix)
Hope that makes sense.
The answer above is updated. Please check!
This works perfect!! Thank you so much for your help!

Sign in to comment.

More Answers (1)

Anna, if you are trying to multiple two 1x25 vectors element-wise then try using a period in front of the multiplication operator.
% Two 1x25 vectors with random values
Np = rand([1,25]);
nyi = rand([1,25]);
% Use '.*' for element-wise calculations instead of '*' which is trying to perform dot-multiplication.
% For '*' to work with two vectors they would need to be sized 1xn and nx1.
Np.*nyi

Categories

Asked:

on 19 Dec 2019

Commented:

on 20 Dec 2019

Community Treasure Hunt

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

Start Hunting!