SOS i keep getting errors in the loop solving by finite difference method.
I either get the following error when i start with i = 2 : N :
diffusion: A(I,J): row index out of bounds; value 2 out of bound 1
error: called from
diffusion at line 37 column 10 % note line change due to edit!
or, I get the following error when i do i = 2 : N :
subscript indices must be either positive integers less than 2^31 or logicals
error: called from
diffusion at line 37 column 10 % note line change due to edit!
Please help
clear all; close all;
% mesh in space
dx = 0.1;
x = 0 : dx : 1;
% mesh in time
dt = 1 / 50;
t0 = 0;
tf = 10;
t = t0 : dt : tf;
% diffusivity
D = 0.5;
% number of nodes
N = 11;
% number of iterations
M = 10;
% initial conditions
if x <= .5 && x >= 0 % note, in octave, you don't need parentheses around the test expression
u0 = x;
elseif
u0 = 1-x;
endif
u = u0;
alpha = D * dt / (dx^2);
for j = 1 : M
for i = 1 : N
u(i, j+1) = u(i, j ) ...
+ alpha ...
* ( u(i-1, j) ...
+ u(i+1, j) ...
- 2 ...
* u(i, j) ...
) ;
end
u(N+1, j+1) = u(N+1, j) ...
+ alpha ...
* ( ...
u(N, j) ...
- 2 ...
* u(N+1, j) ...
+ u(N, j) ...
) ;
% boundary conditions
u(0, :) = u0;
u(1, :) = u1;
u1 = u0;
u0 = 0;
end
% exact solution with 14 terms
%k=14 % COMMENTED OUT
v = (4 / ((k * pi) .^ 2)) ...
* sin( (k * pi) / 2 ) ...
* sin( k * pi * x ) ...
* exp .^ (D * ((k * pi) ^ 2) * t) ;
exact = symsum( v, k, 1, 14 );
error = exact - u;
% plot stuff
plot( t, error );
xlabel( 'time' );
ylabel( 'error' );
legend( 't = 1 / 50' );
Have a look at the edited code I cleaned up for you above and study it.
Don't underestimate the importance of clean, readable code when hunting for bugs.
It will save you more time than it will cost. Especially a week from now when you will need to revisit this code and you will not remember at all what you were trying to do.
Now regarding your errors. (all line references are with respect to the cleaned up code above)
Scenario 1:
In line 29 you initialise u as a single value.
If you start your loop in line 35 starting with i = 2, then as soon as you try to do u(i, j+1), i.e. u(2,2) in the next line, octave will complain that you're trying to index the second row, in an array that so far only contains one row. (in fact, the same will apply for j at this point, since at this point you only have one column as well)
Scenario 2:
I assume the second scenario was a typo and you meant to say i = 1 : N.
If you start with i=1 in the loop, then have a look at line 38: you are trying to get element u(i-1, j), i.e. u(0,1). Therefore octave will complain that you're trying to get the zero element, but in octave arrays start from one and zero is not defined. Attempting to access any array with a zero will result in the error you see (try it in a terminal!).
UPDATE
Also, now that the code is clean, you can spot another bug, which octave helpfully warns you about if you try to run the code.
Look at line 26. There is NO condition in the elseif leg, so octave looks for the next statement as the test condition.
This means that the elseif condition will always succeed as long as the result of u0 = 1-x is non-zero.
This is clearly a bug. Either you forgot to put the condition for the elseif, or more likely, you probably just meant to say else, rather than elseif.
I was referring to the Instant jqGrid book to set up the grid. The noOfPages attribute is calculated as follows.
//Prepare the response
$numberOfPages = ceil( $numberOfRows / $rowsPerPage );
I could see that for 581 records with rowPerPage=25, the noOfPages were appearing as 23.
System.out.println((int)Math.ceil(581/25));//23
I was expecting a value as 24 with the last page containing the records [576-581]. So here, we are missing these 6 records.
It seems you use Java, where ceil of two integer gives integer. I suggest you to look at this theard
To resume the possible solutions are:
int n = (int) Math.ceil((double) a / b));
int n = a / b + (a % b == 0) ? 0 : 1;
int n = (a + b - 1) / b;
Select one which will meet best your requierments
I'm looking for some help in a IT school project. We need to create a programm which can detect roads in a satelite photograph. Our group decided to use a function for detect edges. We search differents solutions and filters on Internet and we decides to use Sobel filter.
We have tried to implement this filter in Scala but it didn't work. We use differents webpages to help us, some of these are on StackOverflow (here). We use this one to help us and try to translate the code : Sobel filter in Ruby.
Start Code --
codeGrey(); // This function transform the RGB in grey level
var sobel_x: Array[Array[Double]] = Array(
Array(-1, 0, 1),
Array(-2, 0, 2),
Array(-1, 0, 1))
var sobel_y: Array[Array[Double]] = Array(
Array(1, 2, 1),
Array(0, 0, 0),
Array(-1, -2, 1))
for (x <- 1 to wrappedImage.height - 2) {
for (y <- 1 to wrappedImage.width - 2) {
var a = (image2D(x - 1)(y - 1) & 0x00FF0000) >> 16
var b = (image2D(x)(y - 1) & 0x00FF0000) >> 16
var c = (image2D(x + 1)(y - 1) & 0x00FF0000) >> 16
var d = (image2D(x - 1)(y) & 0x00FF0000) >> 16
var e = (image2D(x)(y) & 0x00FF0000) >> 16
var f = (image2D(x + 1)(y) & 0x00FF0000) >> 16
var g = (image2D(x - 1)(y + 1) & 0x00FF0000) >> 16
var h = (image2D(x)(y + 1) & 0x00FF0000) >> 16
var i = (image2D(x + 1)(y + 1) & 0x00FF0000) >> 16
var pixel_x =
(sobel_x(0)(0) * a) + (sobel_x(0)(1) * b) + (sobel_x(0)(2) * c) +
(sobel_x(1)(0) * d) + (sobel_x(1)(1) * e) + (sobel_x(1)(2) * f) +
(sobel_x(2)(0) * g) + (sobel_x(2)(1) * h) + (sobel_x(2)(2) * i);
var pixel_y =
(sobel_y(0)(0) * a) + (sobel_x(0)(1) * b) + (sobel_x(0)(2) * c) +
(sobel_y(1)(0) * d) + (sobel_x(1)(1) * e) + (sobel_x(1)(2) * f) +
(sobel_y(2)(0) * g) + (sobel_x(2)(1) * h) + (sobel_x(2)(2) * i);
var res = (Math.sqrt((pixel_x * pixel_x) + (pixel_y * pixel_y)).ceil).toInt
image2D(x)(y) = 0xFF000000 + (res * 65536 + res * 256 + res);
}
}
End Code --
The image returned by this implementation is just an image with black and white pixels and I don't know why. I've got no experience in image processing and we learned Scala 8 weeks ago so that doesn't help.
I'm sorry, my english is not perfect so please forgive me if I didn't write correctly.
I'm not sure I grasp all the details of your solution, anyway here some observation:
consider using vals instead of vars: Scala prefers
immutables and you are not really changing any of those variables.
In scala you can write nested for cycles as a single one over two
variables (check here for details:
Nested iteration in Scala). I think it makes code cleaner.
I presume image2D is the array of arrays in which you are
holding your image. In the last line of your nested for loop you are
changing the current pixel value. This is not good because you will
access that same pixel later when you calculate your a,b,..,h,i
values. The center pixel during current iteration is the side pixel
during next iteration. I think you should write the result in a
different matrix.
This is a tough one to google for. I have an XML document that's a million lines long, and I'm using Ruby to parse it and remove entries I don't care about. One my my criteria is the date created. These XML blocks have funny looking dates in them
<attribute name="datemodified" type="date">362895460.21263897418975830078</attribute>
<attribute name="datecreated" type="date">356831173.15324598550796508789</attribute>
I've never seen dates formatted like that exactly. They look similar to if you did something like Time.now.to_f. Even so I don't know how I'd turn those into Ruby DateTime objects. If you can even identify how these times are created, or what they mean, that would be super helpful.
If it helps, this XML file was originally created by a Mac OS X application known as "Things".
Thanks for reading!
Update: I've created two more entries and recorded the times at which i created them:
From JULY-02-2012 9:57 AM
<attribute name="datemodified" type="date">362941035.01687598228454589844</attribute>
<attribute name="datecreated" type="date">362940986.89370900392532348633</attribute>
From JULY-02-2012 9:58 AM
<attribute name="datemodified" type="date">362941107.69538801908493041992</attribute>
<attribute name="datecreated" type="date">362941080.53793197870254516602</attribute>
I couldn't get down to the second on accuracy, but i did make them about minute apart... Which makes it seem that these are in fact seconds... But... from some random date. Maybe the developer's birthday :)
Doing some quick math, it would appear that the randomish date is right around 2000-12-31 16:09:43 -0800, or perhaps 01/01/01, for ease of memory... And 978336000 in seconds.
The Time.at method translates from seconds since 1970 to a Time instance:
[1] pry(main)> Time.at 362895460.21263897418975830078
=> 1981-07-02 00:17:40 -0400
If that date isn't right, but the units are seconds, you could add a constant to get to the correct date, e.g.
[2] pry(main)> Time.parse('2001-01-01') - Time.at(0)
=> 978325200.0
The numbers look to me like the integer part is a Julian date and the fraction part is the fraction of a day. I haven't investigated that in detail. For reference the code in Saxon for converting date/time from "Julian instant" is:
public static DateTimeValue fromJulianInstant(/*#NotNull*/ BigDecimal instant) {
BigInteger julianSecond = instant.toBigInteger();
BigDecimal microseconds = instant.subtract(new BigDecimal(julianSecond)).multiply(DecimalValue.BIG_DECIMAL_ONE_MILLION);
long js = julianSecond.longValue();
long jd = js / (24L * 60L * 60L);
DateValue date = DateValue.dateFromJulianDayNumber((int)jd);
js = js % (24L * 60L * 60L);
byte hour = (byte)(js / (60L * 60L));
js = js % (60L * 60L);
byte minute = (byte)(js / (60L));
js = js % (60L);
return new DateTimeValue(date.getYear(), date.getMonth(), date.getDay(),
hour, minute, (byte)js, microseconds.intValue(),0 , true);
}
plus
public static DateValue dateFromJulianDayNumber(int julianDayNumber) {
if (julianDayNumber >= 0) {
int L = julianDayNumber + 68569 + 1; // +1 adjustment for days starting at noon
int n = (4 * L) / 146097;
L = L - (146097 * n + 3) / 4;
int i = (4000 * (L + 1)) / 1461001;
L = L - (1461 * i) / 4 + 31;
int j = (80 * L) / 2447;
int d = L - (2447 * j) / 80;
L = j / 11;
int m = j + 2 - (12 * L);
int y = 100 * (n - 49) + i + L;
return new DateValue(y, (byte) m, (byte) d, true);
} else {
// add 12000 years and subtract them again...
DateValue dt = dateFromJulianDayNumber(julianDayNumber +
(365 * 12000 + 12000 / 4 - 12000 / 100 + 12000 / 400));
dt.year -= 12000;
return dt;
}
}
This question already has answers here:
How to convert a column number (e.g. 127) into an Excel column (e.g. AA)
(60 answers)
Closed 9 years ago.
How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?
Edit: A language-agnostic algorithm to determine this is the main goal here.
I once wrote this function to perform that exact task:
public static string Column(int column)
{
column--;
if (column >= 0 && column < 26)
return ((char)('A' + column)).ToString();
else if (column > 25)
return Column(column / 26) + Column(column % 26 + 1);
else
throw new Exception("Invalid Column #" + (column + 1).ToString());
}
Here is the cleanest correct solution I could come up with (in Java, but feel free to use your favorite language):
String getNthColumnName(int n) {
String name = "";
while (n > 0) {
n--;
name = (char)('A' + n%26) + name;
n /= 26;
}
return name;
}
But please do let me know of if you find a mistake in this code, thank you.
A language agnostic algorithm would be as follows:
function getNthColumnName(int n) {
let curPower = 1
while curPower < n {
set curPower = curPower * 26
}
let result = ""
while n > 0 {
let temp = n / curPower
let result = result + char(temp)
set n = n - (curPower * temp)
set curPower = curPower / 26
}
return result
This algorithm also takes into account if Excel gets upgraded again to handle more than 16k columns. If you really wanted to go overboard, you could pass in an additional value and replace the instances of 26 with another number to accomodate alternate alphabets
Thanks, Joseph Sturtevant! Your code works perfectly - I needed it in vbscript, so figured I'd share my version:
Function ColumnLetter(ByVal intColumnNumber)
Dim sResult
intColumnNumber = intColumnNumber - 1
If (intColumnNumber >= 0 And intColumnNumber < 26) Then
sResult = Chr(65 + intColumnNumber)
ElseIf (intColumnNumber >= 26) Then
sResult = ColumnLetter(CLng(intColumnNumber \ 26)) _
& ColumnLetter(CLng(intColumnNumber Mod 26 + 1))
Else
err.Raise 8, "Column()", "Invalid Column #" & CStr(intColumnNumber + 1)
End If
ColumnLetter = sResult
End Function
Joseph's code is good but, if you don't want or need to use a VBA function, try this.
Assuming that the value of n is in cell A2
Use this function:
=MID(ADDRESS(1,A2),2,LEN(ADDRESS(1,A2))-3)
IF(COLUMN()>=26,CHAR(ROUND(COLUMN()/26,1)+64)&CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))
This works 2 letter columns (up until column ZZ). You'd have to nest another if statement for 3 letter columns.
The formula above fails on columns AY, AZ and each of the following nY and nZ columns. The corrected formula is:
=IF(COLUMN()>26,CHAR(ROUNDDOWN((COLUMN()-1)/26,0)+64)&CHAR(MOD((COLUMN()-1),26)+65),CHAR(COLUMN()+64)
Ruby one-liner:
def column_name_for(some_int)
some_int.to_s(26).split('').map {|c| (c.to_i(26) + 64).chr }.join # 703 => "AAA"
end
It converts the integer to base26 then splits it and does some math to convert each character from ascii. Finally joins 'em all back together. No division, modulus, or recursion.
Fun.
FROM wcm:
If you don't want to use VBA, you can use this
replace colnr with the number you want
=MID(ADDRESS(1,colnr),2,LEN(ADDRESS(1,colnr))-3)
Please be aware of the fact that this formula is volatile because of the usage of the ADDRESS function. Volatile functions are functions that are recalculated by excel after EVERY change.
Normally excel recalculates formula's only when their dependent references changes.
It could be a performance killer, to use this formula.
And here is a conversion from the VBScript version to SQL Server 2000+.
CREATE FUNCTION [dbo].[GetExcelColRef]
(
#col_seq_no int
)
RETURNS varchar(5)
AS
BEGIN
declare #Result varchar(5)
set #Result = ''
set #col_seq_no = #col_seq_no - 1
If (#col_seq_no >= 0 And #col_seq_no < 26)
BEGIN
set #Result = char(65 + #col_seq_no)
END
ELSE
BEGIN
set #Result = [dbo].[GetExcelColRef] (#col_seq_no / 26) + '' + [dbo].[GetExcelColRef] ((#col_seq_no % 26) + 1)
END
Return #Result
END
GO
This works fine in MS Excel 2003-2010. Should work for previous versions supporting the Cells(...).Address function:
For the 28th column - taking columnNumber=28; Cells(1, columnNumber).Address returns "$AB$1".
Doing a split on the $ sign returns the array: ["","AB","1"]
So Split(Cells(1, columnNumber).Address, "$")(1) gives you the column name "AB".
UPDATE:
Taken from How to convert Excel column numbers into alphabetical characters
' The following VBA function is just one way to convert column number
' values into their equivalent alphabetical characters:
Function ConvertToLetter(iCol As Integer) As String
Dim iAlpha As Integer
Dim iRemainder As Integer
iAlpha = Int(iCol / 27)
iRemainder = iCol - (iAlpha * 26)
If iAlpha > 0 Then
ConvertToLetter = Chr(iAlpha + 64)
End If
If iRemainder > 0 Then
ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
End If
End Function
APPLIES TO: Microsoft Office Excel 2007 SE / 2002 SE / 2000 SE / 97 SE
I suppose you need VBA code:
Public Function GetColumnAddress(nCol As Integer) As String
Dim r As Range
Set r = Range("A1").Columns(nCol)
GetColumnAddress = r.Address
End Function
This does what you want in VBA
Function GetNthExcelColName(n As Integer) As String
Dim s As String
s = Cells(1, n).Address
GetNthExcelColName = Mid(s, 2, InStr(2, s, "$") - 2)
End Function
This seems to work in vb.net
Public Function Column(ByVal pColumn As Integer) As String
pColumn -= 1
If pColumn >= 0 AndAlso pColumn < 26 Then
Return ChrW(Asc("A"c) + pColumn).ToString
ElseIf (pColumn > 25) Then
Return Column(CInt(math.Floor(pColumn / 26))) + Column((pColumn Mod 26) + 1)
Else
stop
Throw New ArgumentException("Invalid column #" + (pColumn + 1).ToString)
End If
End Function
I took Joseph's and tested it to BH, then fed it 980-1000 and it looked good.
In VBA, assuming lCol is the column number:
function ColNum2Letter(lCol as long) as string
ColNum2Letter = Split(Cells(1, lCol).Address, "$")(0)
end function
All these code samples that these good people have posted look fine.
There is one thing to be aware of. Starting with Office 2007, Excel actually has up to 16,384 columns. That translates to XFD (the old max of 256 colums was IV). You will have to modify these methods somewhat to make them work for three characters.
Shouldn't be that hard...
Here's Gary Waters solution
Function ConvertNumberToColumnLetter2(ByVal colNum As Long) As String
Dim i As Long, x As Long
For i = 6 To 0 Step -1
x = (1 - 26 ^ (i + 1)) / (-25) - 1 ‘ Geometric Series formula
If colNum > x Then
ConvertNumberToColumnLetter2 = ConvertNumberToColumnLetter2 & Chr(((colNum - x - 1)\ 26 ^ i) Mod 26 + 65)
End If
Next i
End Function
via http://www.dailydoseofexcel.com/archives/2004/05/21/column-numbers-to-letters/
Considering the comment of wcm (top value = xfd), you can calculate it like this;
function IntToExcel(n: Integer); string;
begin
Result := '';
for i := 2 down to 0 do
begin
if ((n div 26^i)) > 0) or (i = 0) then
Result := Result + Char(Ord('A')+(n div (26^i)) - IIF(i>0;1;0));
n := n mod (26^i);
end;
end;
There are 26 characters in the alphabet and we have a number system just like hex or binary, just with an unusual character set (A..Z), representing positionally the powers of 26: (26^2)(26^1)(26^0).
FYI T-SQL to give the Excel column name given an ordinal (zero-based), as a single statement.
Anything below 0 or above 16,383 (max columns in Excel2010) returns NULL.
; WITH TestData AS ( -- Major change points
SELECT -1 AS FieldOrdinal
UNION ALL
SELECT 0
UNION ALL
SELECT 25
UNION ALL
SELECT 26
UNION ALL
SELECT 701
UNION ALL
SELECT 702
UNION ALL
SELECT 703
UNION ALL
SELECT 16383
UNION ALL
SELECT 16384
)
SELECT
FieldOrdinal
, CASE
WHEN FieldOrdinal < 0 THEN NULL
WHEN FieldOrdinal < 26 THEN ''
WHEN FieldOrdinal < 702 THEN CHAR (65 + FieldOrdinal / 26 - 1)
WHEN FieldOrdinal < 16384 THEN CHAR (65 + FieldOrdinal / 676 - 1)
+ CHAR (65 + (FieldOrdinal / 26) - (FieldOrdinal / 676) * 26 - 1)
ELSE NULL
END
+ CHAR (65 + FieldOrdinal % 26)
FROM TestData
ORDER BY FieldOrdinal
I currently use this, but I have a feeling that it can be optimized.
private String GetNthExcelColName(int n)
{
String firstLetter = "";
//if number is under 26, it has a single letter name
// otherwise, it is 'A' for 27-52, 'B' for 53-78, etc
if(n > 26)
{
//the Converts to double and back to int are just so Floor() can be used
Double value = Convert.ToDouble((n-1) / 26);
int firstLetterVal = Convert.ToInt32(Math.Floor(value))-1;
firstLetter = Convert.ToChar(firstLetterValue + 65).ToString();
}
//second letter repeats
int secondLetterValue = (n-1) % 26;
String secondLetter = Convert.ToChar(secondLetterValue+65).ToString();
return firstLetter + secondLetter;
}
=CHAR(64+COLUMN())