I have been working on a fortran code to convert it into the matlab. I am facing some issues with dimensioning! Following is the code which is giving me error
do 10 p = 1,m
d(p) = 0.d0
d(p) = x - x1(i,p) - x2(i,p) -
& double_sum(i,p,n,m,str,mot)
10 continue
double_sum = 0.d0
do 10 j = 1,m
do 20 k = 1,n
if (k .eq. i) then
else
double_sum = double_sum + mot(k,j,i,p)*str(k,j)
endif
20 continue
10 continue
to which I converted it into matlab as:
for p=1:m
d(p)=0;
double_sum = 0;
for j=1:m
for k=1:n
if k==i
else
double_sum = double_sum + mot(k,j,i,p)*str(k,j);
end
end
end
d(p)=x - x1(i,p) - x2(i,p)-double_sum(i,p,n,m,str,mot);
end
I am getting error of "index exceeding matrix".
The error line is for this part of my code:
d(p)=x - x1(i,p) - x2(i,p)-double_sum(i,p,n,m,str,mot);
So if I ignore double_sum(i,p,n,m,str,mot); this part, code runs perfectly.
I know the double_sum matrix is of 6D which looks suspicious to me, but I would like to have your support to successfully port this piece of fortran code.
Note:Asked the same question on matlab forum. But stackoverflow have more chances of people worked on fortran 77. Hence asking it here.
If the Fortran code in the Question is really everything, it may be a very rough snippet that explains how to calculate array d(:)
do 10 p = 1, m
d( p ) = x - x1( i, p ) - x2( i, p ) - double_sum( i, p, n, m, str, mot )
10 continue
with a function double_sum() defined by
double precision function double_sum( i, p, n, m, str, mot )
implicit none
integer, intent(in) :: i, p, n, m
double precision, intent(in) :: str( n, m ), mot( n, m, ?, ? )
integer j, k
double_sum = 0.d0
do 10 j = 1, m
do 20 k = 1, n
if (k .eq. i) then
else
double_sum = double_sum + mot( k, j, i, p ) * str( k, j )
endif
20 continue
10 continue
end
though it is definitely better to find the original Fortran source to check the context...(including how i and d(:) are used outside this code). Nevertheless, if we use the above interpretation, the corresponding Matlab code may look like this:
for p = 1:m
double_sum = 0;
for j = 1:m
for k = 1:n
if k == i
else
double_sum = double_sum + mot( k, j, i, p ) * str( k, j );
end
end
end
d( p ) = x - x1( i, p ) - x2( i, p ) - double_sum; % <--- no indices for double_sum
end
There is also a possibility that double_sum() is a recursive function, but because we cannot use the function name as the result variable (e.g. this page), it may be OK to exclude that possibility (so the Fortran code has two scopes, as suggested by redundant labels 10).
There is an error in your loops. The fortran code runs one loop over p=1:m, whose end is marked by the continue statement. Then, two nested loops over j and k follow.
Assuming, you know the size of all your arrays beforehand and have initialized them to the correct size (which may not be the case given your error statement) this is more along the lines of the fortran example you posted.
d = zeros(size(d));
for p=1:m
d(p)=x - x1(i,p) - x2(i,p)-double_sum(i,p,n,m,str,mot);
end
% add a statement here to set all entries of double sum to zero
double_sum = zeros(size(double_sum))
for j=1:m
for k=1:n
if k==i
else
double_sum = double_sum + mot(k,j,i,p)*str(k,j);
end
end
end
It is a little hard to give advice without knowledge of more parts of the code. are mot and str and double_sum functions? Arrays? The ambiguous choice of brackets in those two languages are hardly OPs fault, but make it necessary to provide further input.
Related
Hey i have an issuse with plotting my own function in scilab.
I want to plot the following function
function f = test(n)
if n < 0 then
f(n) = 0;
elseif n <= 1 & n >= 0 then
f(n) = sin((%pi * n)/2);
else
f(n) = 1;
end
endfunction
followed by the the console command
x = [-2:0.1:2];
plot(x, test(x));
i loaded the function and get the following error
!--error 21
Invalid Index.
at line 7 of function lala called by :
plot(x, test(x))
Can you please tell me how i can fix this
So i now did it with a for loop. I don't think it is the best solution but i can't get the other ones running atm...
function f = test(n)
f = zeros(size(n));
t = length(n);
for i = 1:t
if n(i) < 0 then
f(i) = 0;
elseif n(i) <= 1 & n(i) >= 0
f(i) = sin((%pi * n(i)/2));
elseif n(i) > 1 then
f(i) = 1;
end
end
endfunction
I guess i need to find a source about this issue and get used with the features and perks matlab/scilab have to over :)
Thanks for the help tho
The original sin is
function f = test(n)
(...)
f(n) = (...)
(...)
endfunction
f is supposed to be the result of the function. Therefore, f(n) is not "the value that the function test takes on argument n", but "the n-th element of f". Scilab then handles this however it can; on your test case, it tries to access a non-integer index, which results in an error. Your loop solution solves the problem.
Replacing all three f(n) by f in your first formulation makes it into something that works... as long as the argument is a scalar (not an array).
If you want test to be able to accept vector arguments without making a loop, the problem is that n < 0 is a vector of the same size as n. My solution would use logical arrays for indexing each of the three conditions:
function f = test(n)
f = zeros(size(n));
negative = (n<0);//parentheses are optional, but I like them for readability
greater_than_1 = (n>1);
others = ~negative & ~greater_than_1;
f(isnegative)=0;
f(greater_than_1)=1;
f(others) = sin(%pi/2*n(others));
endfunction
I'm trying to optimize the performance (e.g. speed) of my code. I 'm new to vectorization and tried myself to vectorize, but unsucessful ( also try bxsfun, parfor, some kind of vectorization, etc ). Can anyone help me optimize this code, and a short description of how to do this?
% for simplify, create dummy data
Z = rand(250,1)
z1 = rand(100,100)
z2 = rand(100,100)
%update missing param on the last updated, thanks #Bas Swinckels and #Daniel R
j = 2;
n = length(Z);
h = 0.4;
tic
[K1, K2] = size(z1);
result = zeros(K1,K2);
for l = 1 : K1
for m = 1: K2
result(l,m) = sum(K_h(h, z1(l,m), Z(j+1:n)).*K_h(h, z2(l,m), Z(1:n-j)));
end
end
result = result ./ (n-j);
toc
The K_h.m function is the boundary kernel and defined as (x is scalar and y can be vector)
function res = K_h(h, x,y)
res = 0;
if ( x >= 0 & x < h)
denominator = integral(#kernelFunc,-x./h,1);
res = 1./h.*kernelFunc((x-y)/h)/denominator;
elseif (x>=h & x <= 1-h)
res = 1./h*kernelFunc((x-y)/h);
elseif (x > 1 - h & x <= 1)
denominator = integral(#kernelFunc,-1,(1-x)./h);
res = 1./h.*kernelFunc((x-y)/h)/denominator;
else
fprintf('x is out of [0,1]');
return;
end
end
It takes a long time to obtain the results: \Elapsed time is 13.616413 seconds.
Thank you. Any comments are welcome.
P/S: Sorry for my lack of English
Some observations: it seems that Z(j+1:n)) and Z(1:n-j) are constant inside the loop, so do the indexing operation before the loop. Next, it seems that the loop is really simple, every result(l, m) depends on z1(l, m) and z2(l, m). This is an ideal case for the use of arrayfun. A solution might look something like this (untested):
tic
% do constant stuff outside of the loop
Zhigh = Z(j+1:n);
Zlow = Z(1:n-j);
result = arrayfun(#(zz1, zz2) sum(K_h(h, zz1, Zhigh).*K_h(h, zz2, Zlow)), z1, z2)
result = result ./ (n-j);
toc
I am not sure if this will be a lot faster, since I guess the running time will not be dominated by the for-loops, but by all the work done inside the K_h function.
I would like to use the LAPACK routines for factorisation and inversion of matrices using the fully packed rectangular format, as this requires only n(n+1)/2 elements to be stored for a symmetric nxn matrix. So far, I am setting up the matrix in 'packed' format and transform it calling routine DTPTTF. However, this requires a second array. I would like to build my matrix directly in fully packed rectangular format (to save on space) - is there an 'addressing' function which will give me the position of the i,j-th element? or could somebody point me to the relevant formula?
to partly answer my own question: inspecting the source code of DTPTTF and the example given therein, I've worked out the adress for one of the four possible constellations (the only one I need), namely uplo ='L' and trans ='N'. below is my fortran function:
! ==================================== ! returns address for RFP format
integer function ijfprf( ii, jj, n ) ! for row jj and column ii
! ==================================== ! for UPLO = 'L' and TRANSR = 'N' only!
implicit none
integer, intent(in) :: ii, jj, n
integer :: i, j, k, n1, k1
if( ii <= jj ) then
i = ii; j = jj
else
i = jj; j = ii
end if
k = n/2
if( mod(n,2) == 0 ) then ! n even
n1 = n + 1
if( i <= k ) then
ijfprf = 1 + (i - 1) * n1 + j
else
ijfprf = ( j - k - 1 ) * n1 + i - k
end if
else ! n odd
k1 = k + 1
if( i > k1 ) then
ijfprf = ( j - k1 ) * n + i - k1
else
ijfprf = ( i - 1 ) * n + j
end if
end if
return
end function ijfprf
I have a code for finding the bisection (and it finally works!), but I need to include 3 more things:
output- Root History a vector containing the sequence of midpoints obtained by the algorithm
output- the absolute value of the function
f(x) at r, i.e., fRoot = f(r) input- max iterations
function [R, E] = myBisection(f, a, b, tol)
m = (a + b)/2;
R = m;
E = abs(f(m));
while E(end) > tol
if sign(f(a)) == sign(f(m))
a = m;
else
b = m;
end
m = (a + b)/2;
R = [R, m];
E = [E, abs(f(m))];
end
how do I do this? thanks!!
I have corrected indents an you can see that you've left out end from the end of the function. (it is optional but best not to leave those things out so you know you did not mean to write couple lines to the end but you forgot it.)
R and E should be returned now, if you call myBisection apropriately, that is
[R, E] = myBisection(f, a, b, tol);
If you just call
myBisection(f, a, b, tol)
it will only return R.
To add a limit on the number of iterations, you change while's condition like so:
iter=0;
while (E(end) > tol) && (iter<max_iter)
iter = iter+1;
% ...
end
or it is better to do it in a for loop, with an if plus break:
for iter=1:max_iter
if(E(end) <= tol), break, end;
% ...
end
I keep getting this error in Matlab:
Attempted to access r(0,0); index must be a positive integer or
logical.
Error in ==> Romberg at 15
I ran it with Romberg(1.3, 2.19,8)
I think the problem is the statement is not logical because I made it positive and still got the same error. Anyone got some ideas of what i could do?
function Romberg(a, b, n)
h = b - a;
r = zeros(n,n);
for i = 1:n
h = h/2;
sum1 = 0;
for k = 1:2:2^(i)
sum1 = sum1 + f(a + k*h);
end
r(i,0) = (1/2)*r(i-1,0) + (sum1)*h;
for j = 1:i
r(i,j) = r(i,j-1) + (r(i,j-1) - r(i-1,j-1))/((4^j) - 1);
end
end
disp(r);
end
function f_of_x = f(x)
f_of_x = sin(x)/x;
end
There are two lines where you're using 0 to index, which you can't in Matlab:
r(i,0) = (1/2)*r(i-1,0) + (sum1)*h;
and
r(i,j) = r(i,j-1) + (r(i,j-1) - r(i-1,j-1))/((4^j) - 1);
when j==1 or i==1.
I suggest that you run your loops starting from 2, and replace the exponents i and j with (i-1) and (j-1), respectively.
As an aside: You could write the loop
for k = 1:2:2^(i)
sum1 = sum1 + f(a + k*h);
end
as
k = 1:2:2^i;
tmp = f(a + k*h);
sum1 = sum(tmp);
if you write f_of_x as
sin(x)./x
In MATLAB, vectors and matrices are indexed starting from 1. Therefore, the very first line of your code is invalid because the index on r is 0.
You have zero subscripts in
r(i,0) = (1/2)*r(i-1,0) + (sum1)*h;
This is impossible in MATLAB -- all indices start form 1.