score:6
edit: the code below will work, but it's not as readable as using an explicit method. linq is great where it definitely adds to readability... but this isn't one of those cases.
this is a briefer version of cms's answer - the extra let
isn't required, and when you're just doing a projection it's simpler to just use dot notation:
int[] result = enumerable.range(0, a.length)
.select(i => a[i] * b[i])
.toarray();
an alternative is to use the form of select which takes an index:
int[] result = a.select((value, index) => value * b[index])
.toarray();
score:0
check out this msdn article on the upcoming plinq (parallel linq). from the article, here is an example of using plinq to parallelize matrix multiplication:
void parmatrixmult(int size, double[,] m1, double[,] m2, double[,] result)
{
parallel.for( 0, size, delegate(int i) {
for (int j = 0; j < size; j++) {
result[i, j] = 0;
for (int k = 0; k < size; k++) {
result[i, j] += m1[i, k] * m2[k, j];
}
}
});
}
it's using linq and a lambda! and as a bonus it's spread across processors.
score:0
you can write a simple extension that works with matrices of any rank.
public static class twodimensionalarrayextensions
{
public static int[][] multiplyby(this int[][] leftmatrix, int[][] rightmatrix)
{
if (leftmatrix[0].length != rightmatrix.length)
{
return null; // matrices are of incompatible dimensions
}
return leftmatrix.select( // goes through <leftmatrix matrix> row by row
(leftmatrixrow, leftmatrixrowindexthatisnotused) =>
rightmatrix[0].select( // goes through first row of <rightmatrix> cell by cell
(rightfirstrow, rightmatrixcolumnindex) =>
rightmatrix
.select(rightrow => rightrow[rightmatrixcolumnindex]) // selects column from <rightmatrix> for <rightmatrixcolumnindex>
.zip(leftmatrixrow, (rowcell, columncell) => rowcell * columncell) // does scalar product
.sum() // computes the sum of the products (rowcell * columncell) sequence.
)
.toarray() // the new cell within computed matrix
)
.toarray(); // the computed matrix itself
}
}
here are some test values:
// test1
int[][] a = { new[] { 1, 2, 3 } };
int[][] b = { new[] { 1 }, new[] { 2 }, new[] { 3 } };
int[][] result = a.multiplyby(b);
// test2
int[][] a = { new[] { 1 }, new[] { 2 }, new[] { 3 } };
int[][] b = { new[] { 1, 2, 3 } };
int[][] result = a.multiplyby(b);
// test3
int[][] a = new int[][] { new[] { 1, 2 }, new[] { 2, 2 }, new[] { 3, 1 } };
int[][] b = new int[][] { new[] { 1, 1, 1 }, new[] { 2, 3, 2 } };
int[][] result = a.multiplyby(b);
score:0
if the right matrix is transposed beforehand, multiplication can be expressed more elegantly as follows.
int[][] multiply(int[][] left, int[][] right) =>
left.select(lr =>
right
.select(rr =>
lr.zipped(rr, (l, r) => l * r).sum())
.toarray())
.toarray();
score:2
you can do something like this:
int[] a = {10, 20, 30};
int[] b = {2, 4, 10};
if (a.length == b.length)
{
int[] result = (from i in enumerable.range(0, a.length)
let operation = a[i]*b[i]
select operation).toarray();
}
but i recommend you if you will work with matrices and more advanced mathematical topics to get a good math library, like nmath or search for a matrix class implementation, there are many out there...
score:2
there is nothing built in, but you can always write your own functions. the first one below is a simple extension method doing what you want. the second allows you to specify the function to apply:
class program
{
public static void main(string[] args)
{
int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a.matrixmultiply(b);
int[] c2 = a.zip(b, (p1, p2) => p1 * p2);
}
}
public static class extension
{
public static int[] matrixmultiply(this int[] a, int[] b)
{
// todo: add guard conditions
int[] c = new int[a.length];
for (int x = 0; x < a.length; x++)
{
c[x] = a[x] * b[x];
}
return c;
}
public static r[] zip<a, b, r>(this a[] a, b[] b, func<a, b, r> func)
{
// todo: add guard conditions
r[] result = new r[a.length];
for (int x = 0; x < a.length; x++)
{
result[x] = func(a[x], b[x]);
}
return result;
}
}
score:5
using the zip function (new to .net 4.0) details here:
int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a.zip(b, (a1, b1) => a1 * b1).toarray();
until .net 4 comes out you can use the zip implementation from the link above.
Source: stackoverflow.com
Related Query
- Can you use LINQ or lambdas to perform matrix operations?
- Can you use LINQ types and extension methods in IronPython?
- How can I switch that code to use LINQ
- Can you use linq to see if two IEnumerables of data contain any common entries?
- Can you use LINQ extension method operators in an ASP.NET databinding expression?
- Can you use LINQ with in memory objects rather than SQL Server queries to improve performance?
- How can you use LINQ to find Azure AD users with specific licenses using the Azure AD Graph API Client Library 2.0
- How can you use LINQ to cast from a collection of base class objects to a filtered list of their respective subclasses?
- Using Linq to build a graph class; can you make this code look better?
- How can you use Linq result with RDLC report?
- Can I use a LINQ IEnumerable result as the data source for a Gtk.TreeView?
- Can I Use The Same Linq Code to Query for Different Conditions?
- How can you use a LINQ Lambda Where Property Count = Something
- Can you use a List to configure a selector in LINQ join query?
- Can you include more than just one relationship level using lambdas in linq to entities
- Can you use LINQ to do a process such as converting part of a list and assigning to another?
- Can you use Linq to find relationships between elements in a collection?
- How do you use (or can you use) the Linq Intersect method on a child list member of an IEnumerable?
- How do you perform a left outer join using linq extension methods
- How do you perform a CROSS JOIN with LINQ to SQL?
- How can I use Linq in a T4 template?
- How can you handle an IN sub-query with LINQ to SQL?
- Can I declare / use some variable in LINQ? Or can I write following LINQ clearer?
- How do you use LINQ to find the duplicate of a specific property?
- How do you use LINQ with Sqlite
- Can LINQ use binary search when the collection is ordered?
- How can I use linq to sort by multiple fields?
- How can I use LINQ to find a DataGridView row?
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- Can I use a TryParse inside Linq Comparable?
More Query from same tag
- Entity to DropDownListItem using Lambda expressions in method
- C# Linq create a list of derived class inside Group By
- Doing an 'OrderByDescending' on each child List in a Parent List
- C# string format unknown size
- Performance linq group by with count
- Handling large SQL queries with LINQ
- How to optimize the query - Ef core
- LINQ - How to modify the select depending on value that DB would return
- dropdownlistfor not selecting what's supposed to be selected upon page load
- LINQ - joining two tables and getting the values from the right part of the join if it exists throw exception
- Why does the c#(web) linq syntax is different in vb(windows) linq syntax?
- Find index of last occurrence of each distinct zipcode in collection
- Is there a way to construct database query, where I can apply condition based on values in a list?
- Linq with join query returning only one record
- Sort list of lists using LINQ so high score is first then lastname and firstname in alphabetic order
- EF does not lazy load Views
- LINQ select depending on inner collection value
- Issue with OrderBy type cannot be inferred from the usage
- break an IEnumerable<int> query which uses Enumerable.Range
- How to call a function from Linq statement without a return value?
- How to send column data as a comma separated string from stored procedure?
- How to Join two columns from table A with two columns from table B - Linq join MVC
- Using "from in" in a LinqSpecs specification?
- Get record index column in linq select
- Is there any difference in execution for async lambda?
- Add new record to linq query result
- Select common value in navigation table using LINQ lambda expression
- Linq query with a Join, not returning the correct results
- How can i cast IQueryable<> query to IQueryable<obj.getType()>?
- C# list.remove(item) removes item from other list I want