<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Calling Excel from NMath Archives - CenterSpace</title>
	<atom:link href="https://www.centerspace.net/tag/calling-excel-from-nmath/feed" rel="self" type="application/rss+xml" />
	<link>https://www.centerspace.net/tag/calling-excel-from-nmath</link>
	<description>.NET numerical class libraries</description>
	<lastBuildDate>Tue, 01 Mar 2016 21:45:00 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>
<site xmlns="com-wordpress:feed-additions:1">104092929</site>	<item>
		<title>Using C# and ExcelDNA to call .NET Libraries</title>
		<link>https://www.centerspace.net/using-c-and-exceldna-to-call-net-libraries</link>
					<comments>https://www.centerspace.net/using-c-and-exceldna-to-call-net-libraries#comments</comments>
		
		<dc:creator><![CDATA[CenterSpace]]></dc:creator>
		<pubDate>Fri, 14 Jan 2011 05:00:21 +0000</pubDate>
				<category><![CDATA[Excel]]></category>
		<category><![CDATA[NMath Tutorial]]></category>
		<category><![CDATA[c# math with excel]]></category>
		<category><![CDATA[Calling Excel from NMath]]></category>
		<category><![CDATA[Curve fitting with Excel]]></category>
		<category><![CDATA[ExcelDNA math]]></category>
		<category><![CDATA[ExcelDNA NMath]]></category>
		<category><![CDATA[NMath Excel]]></category>
		<guid isPermaLink="false">http://www.centerspace.net/blog/?p=3058</guid>

					<description><![CDATA[<p><img src="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic2.gif" alt="Excel and NMath interop"  class="excerpt" /><br />
The outcome of these blog articles should illustrate that Excel can become a powerful tool to quickly access a comprehensive .NET library without needing a large supporting programming environment.  This made possible by Govert van Drimmelen's freeware tool ExcelDNA.  ExcelDNA can interpret VB, C#, and F# instructions stored in a text file as Excel is loaded eliminating the need for a separate compiler.  In our last blog, we named our file <strong>NMathExcel.dna</strong> to hold our VB code.  Below, I have provided C# code that performs the same matrix functions as the VB code in our <a href="https://www.centerspace.net/blog/nmath/calling-external-net-libraries-from-excel/">previous post</a>.</p>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/using-c-and-exceldna-to-call-net-libraries">Using C# and ExcelDNA to call .NET Libraries</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In my <a href="/calling-external-net-libraries-from-excel/">last post</a>, I demonstrated calling NMath from Excel using ExcelDNA and Visual Basic (VB) code.  In this blog post, we will duplicate that functionality using C# instead of Visual Basic.  In addition we will use the functionality of NMath to enabled the marshaling of data between Excel and NMath, and provide some additional code examples.</p>
<p>The outcome of these blog articles should illustrate that Excel can become a powerful tool to quickly access a comprehensive .NET library such as CenterSpace&#8217;s NMath without needing a large supporting programming environment.  This is all made possible by Govert van Drimmelen&#8217;s freeware tool ExcelDNA.  ExcelDNA can interpret VB, C#, and F# instructions stored in a text file as Excel is loaded eliminating the need for a separate compiler.  ExcelDNA does require the text file to have the extension <code>.DNA</code>.  I recommend using an editor like <a href="https://notepad-plus-plus.org/">NotePad++</a> to edit this file.  In our last blog post, we named our file <strong>NMathExcel.dna</strong> to hold our VB code.  Below, I have provided C# code that performs the same functions as the VB code in our <a href="/calling-external-net-libraries-from-excel/">previous post</a>.  This code below provides examples on how to use several basic routines in NMath.</p>
<pre lang="csharp">

<DnaLibrary Language="CS">
<Reference Name="CenterSpace.NMath.Core" />
<Reference Path="C:\Program Files\CenterSpace\NMath 4.1\Assemblies\NMath.dll" />
<Reference Path="C:\Program Files\CenterSpace\NMath 4.1\Assemblies\NMathShared.dll" />
<Reference Name="CenterSpace.NMath.Stats" />
<Reference Path="C:\Program Files\CenterSpace\NMath Stats 3.2\Assemblies\NMathStats.dll" />

<![CDATA[
 	 using ExcelDna.Integration;
 	 using CenterSpace.NMath.Core;
  	 using CenterSpace.NMath.Stats;

  	public class NMathExcelFunctions
  	{
  		[ExcelFunction(Description="Returns x raised to the y power")]
  		public static double NPower(double x, double y)
  		{
  			return NMathFunctions.PowFunction(x, y);
  		}
  		[ExcelFunction(IsVolatile=true)]
  		public static double NRand()
  		{
  			RandGenMTwist randomGenMTwist = new RandGenMTwist();
  			return randomGenMTwist.Next53BitRes();
  		}
  		[ExcelFunction(Description="Binomial Distribution: Number of Successes, Trials, Probability, Cumulative is True or False")]
  		public static double NBinomDist(int NSuccess, int NTrials, double Prob, bool Cumul)
  		{
 	 		BinomialDistribution binomialDistribution = new BinomialDistribution();
  			binomialDistribution.N = NTrials;
  			binomialDistribution.P = Prob;
  			if (Cumul)
  				return binomialDistribution.CDF(NSuccess);
  			else
  				return binomialDistribution.PDF(NSuccess);
  		}
  		[ExcelFunction(Description="Create a r by c matrix and fill with Random # between L and B")]
  		public static double[,] NDoubleMatrixRand(int rsize, int csize, int RandLBx, int RandUBx)
  		{
  			RandGenUniform randomGenUniform = new RandGenUniform(RandLBx,RandUBx);
  			randomGenUniform.Reset(0x124);
  			DoubleMatrix TempAr = new DoubleMatrix(rsize,csize,randomGenUniform);
  			return TempAr.ToArray();
  		}
  	}
]]&gt;
</DnaLibrary>
</pre>
<p>In reviewing the differences between the VB and C# versions, the first order of business was to add the language specification to &#8220;CS&#8221; for C# so that ExcelDNA knows to switch from the default language of VB. Aside from the obvious differences between the two languages, we have added a reference to our NMathShared assembly and an explicit reference to using ExcelDNA.Integration.  In general, the C# code is slightly simpler than VB and enables very simple code to call the library.  In our C# sample code function for creating a <code>DoubleMatrix</code> with a random generation, we used the library&#8217;s built in conversion function <code>ToArray()</code> to marshal the data into an array format for Excel.  Using NMath&#8217;s built-in array handling capabilities we can simply copy data in and out in the proper formats.  This illustrates the ease by which we can utilize the NMath math libraries and Excel.</p>
<p>To further demonstrate this capability, we can add the following code to our NMathExcel.dna text file that calls the matrix transpose function in NMath.  We will show how to create array data in Excel, pass it to the library in the proper format, and then return a result for display.</p>
<pre lang="csharp">
   public static double[,] NDoubleMatrixTranspose(double[,] InputAr)
   {
      DoubleMatrix TempAr = new DoubleMatrix(InputAr);
     TempAr = TempAr.Transpose();
      return TempAr.ToArray();
   }
</pre>
<p>Make sure you close Excel and reopen it after saving your code changes to the .DNA file so that ExcelDNA has the opportunity to incorporate the new code.</p>
<p>We can now send our library a range of data cells to be acted on and display the result.  In the following screen shot I show setting up a 5 by 5 range with values to be transposed.</p>
<p><a href="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic1.gif"><img decoding="async" width="829" height="603" src="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic1.gif" alt="" title="Creating a 5x5 matrix with data" class="alignnone size-full wp-image-3071" srcset="https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic1.gif 829w, https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic1-300x218.gif 300w" sizes="(max-width: 829px) 100vw, 829px" /></a></p>
<p>We can now select an available empty cell to insert our transpose computation.  The following screenshot shows selecting the input range for calling our NMath transpose function.</p>
<p><a href="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic2.gif"><img decoding="async" loading="lazy" width="993" height="698" src="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic2.gif" alt="" title="Selecting a range of value to send to the Transpose function  class="alignnone size-full wp-image-3073" srcset="https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic2.gif 993w, https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic2-300x210.gif 300w" sizes="(max-width: 993px) 100vw, 993px" /></a></p>
<p>As in our previous blog, the returned result is stored in a single cell and only one value is displayed.  As a quick review to display the full result, first paint (select) the area for the data to be displayed with the function call in the upper left hand corner, then press the F2 key, next press Ctrl-Shift (hold), followed by the Enter key &#8211; this will build the array formula to populate the selected area with the result.  Your result should look like the following screen.</p>
<p><a href="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic3.gif"><img decoding="async" loading="lazy" width="773" height="555" src="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic3.gif" alt="" title="Completed example of the matrix transpose function" class="alignnone size-full wp-image-3074" srcset="https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic3.gif 773w, https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic3-300x215.gif 300w" sizes="(max-width: 773px) 100vw, 773px" /></a></p>
<p>As a further example of what is possible, we can tackle an least squares example from the NMath documentation.  The problem is to calculate the residual norm square using the Cholesky method, something that would be awkward to do natively in Excel alone. In this example the inputs are the number of rows and columns of a <code>DoubleMatrix</code> uniformly filled with random numbers. To accomplish this we need to add the following code to our DNA text file.</p>
<pre lang="csharp">
using CenterSpace.NMath.Matrix;
  .
  .
public static object NDoubleCholeskyLeastSqRNS(int rsize, int csize, int RandLBx, int RandUBx)
{
	RandGenUniform randomGenUniform = new RandGenUniform(RandLBx,RandUBx);
	randomGenUniform.Reset(0x124);
	DoubleMatrix TempAr = new DoubleMatrix(rsize,csize,randomGenUniform);
	DoubleCholeskyLeastSq cholLsq = new DoubleCholeskyLeastSq(TempAr);
	if (cholLsq.IsGood)
	{
 		DoubleVector b = new DoubleVector(TempAr.Rows,randomGenUniform);
		DoubleVector x = cholLsq.Solve(b);
		return cholLsq.ResidualNormSqr(b);
	}
	else
		return "The random matrix doesn't have full rank";
}
</pre>
<h3> Summary </h3>
<p>Approaching the complex computations with Excel by performing the necessary computation by calling a C# library with data passed in from Excel, creates a robust approach to solving problems.   The following screenshot shows how providing our function with the input parameters from the example produces the desired result.</p>
<p><a href="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic4.gif"><img decoding="async" loading="lazy" width="870" height="418" src="https://www.centerspace.net/blog/wp-content/uploads/2011/01/Blog2pic4.gif" alt="" title="Using the Cholesky Least Squares method in Excel to solve." class="alignnone size-full wp-image-3077" srcset="https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic4.gif 870w, https://www.centerspace.net/wp-content/uploads/2011/01/Blog2pic4-300x144.gif 300w" sizes="(max-width: 870px) 100vw, 870px" /></a></p>
<p>If we tried to implement the solution line by line in Excel, we would be loosing the power of an object language like C# and powerful third-party .NET libraries, and increasing the generation of tedious Excel code without a strong development environment. </p>
<p>To wrap up, combining Excel, ExcelDNA, and the CenterSpace&#8217;s NMath libraries can be used to quickly generate solutions to complex problems without an extensive programming environment.  In my next blog, I plan to solve a curve fitting example with this approach and using more of Excel features to display the results.</p>
<p>Mike Magee</p>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/using-c-and-exceldna-to-call-net-libraries">Using C# and ExcelDNA to call .NET Libraries</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.centerspace.net/using-c-and-exceldna-to-call-net-libraries/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3058</post-id>	</item>
	</channel>
</rss>
