1.- the product
need not be in a for loop. If you define p and h same size, in MATLAB you simply do element wise product, like this:
add ; at the end of each command line if processing large inputs, to suppress command line echo, that is most of time slower than the processing itself
2.- you are right regarding the line
for j=1:n
cum_CO2inj(j)=function(p(i), HCPV(i),j)
..
simply repeats 100 times because of the unnecessary first for loop.
3.- so you say you want
output .. or a matrix of size 100 by 30
let's allocate space
n=30;
cumCO2inj=zeros(100,n);
one way of doing it would be
for k=1:1:100
cum_CO2inj(k,:)=function2(p(k),HCPV(k))
end
where function2 already takes into account the length n=30 or n=29, doesn't seem that there is neither need here for the input j
Show me the function and I will help you modify it to avoid having to input your vector index j.
Another way would be with bsxfun
where A and B are input matrices of same size, and fun is either a built-in or custom function that processes element wise each pair of elements of A and B.
bsxfun built-in functions
if your function is not any of the built-in basic ones listed in this table, you can define a custom function for bsxfun for instance like this:
function2 = @(A,B) A.*sin(B);
A = 1:7;
B = pi*[0 1/4 1/3 1/2 2/3 3/4 1].';
C = bsxfun(function2,A,B)
or you can put your function2 in a separate file named function2.m
then you would have something like this
for k=1:1:100
cum_CO2inj(k,:)=bsxfun(function2,p,HCPV)
end
All above said helps but still doesn't solve the main problem:
4.- there would still be 100 times the same processed result, because same apparently randomly generated vectors are used in all 100 outputs.
This happens because you do not include the random generation inside the for loop that generates cum_CO2inj.
Try this
function2 = @(A,B) A.*sin(B);
for k=1:1:100
p=rand(..)
h=rand(..)
HCPV=p.*h
cum_CO2inj(k,:)=function2(p,HCPV)
end
or
function3 = @(A,B) A.*sin(B);
for k=1:1:100
p=rand(..)
h=rand(..)
HCPV=p.*h
cum_CO2inj(k,:)=bsxfun(function2,p,HCPV)
end
or
p=randi([-10 10],1,10,100)
h=randi([-10 10],1,10,100)
HCPV=p.*h
cum_CO2inj=bsxfun(function3,p,HCPV)
In the more compact last option function3 may be quite the same as function2 or your original function, but it has to take into account that you have already generated all 100 random vectors, so there is no need for any for loop at all here.
I say again, if you show the function you want to implement I will check it and modify accordingly to make it work with the changes here mentioned.
Please if you find my answer of any help would you be so kind to mark my answer as accepted answer?
thanks in advance.
To any other reader, if you find my answer of any help would you please give it a thumbs-up click? thanks in advance.
Appreciating time and attention
John BG