user2654929
user2654929

Reputation: 11

How to apply function involving elements in a column of a table

I have a n x m matrix of data.

How do I create a function that has a sum that includes elements of each column, such that if I input a value, I would get a 1 x m row (where m > 100)?

More specifically, I am computing a discrete Fourier transform of the data in each column that should work for any input frequency I put in.

Here is my code for a single column:

(* Length of time data *)
n = Length[t]

(* Compute discrete fourier transform at specified frequency f *)
DFT[f_] := (t[[2]] - t[[1]]) Sum[
    mat[[i + 1]] * Exp[2 Pi I f mat[[i + 1]]], {i, 0, n - 1}];

I'd like to extend this to m columns so that if I want to compute the DFT for a given column at a specific frequency, I can just extract an element of a 1 x m row.

I've considered a function like Map, but it seems like it'll directly apply my function by inputting the value of each element in the row, which isn't exactly what I want.

Upvotes: 1

Views: 477

Answers (2)

Aaa
Aaa

Reputation: 1854

It seems like you just need to get the column. The way that matrices are stored in Mathematica has the first coordinate as the row and the second as the column. All coordinates start at 1, not 0. To get an element at a specific coordinate, you use matrix[[row, column]]. If you want a whole row, matrix[[row]]. If you want a column, matrix[[All, column]]. Accordingly, here is one way you might adjust the DFT function:

DFT[f_, list_] := (t[[2]] - t[[1]]) Sum[
    list[[i]] * Exp[2 Pi I f list[[i]]], {i, 1, n}];

yourColumnDFT = DFT[f, matrix[[All, columnNumber]]]

In fact, you can make this even simpler by removing the call to Sum because these operations automatically map over lists by index:

DFT[f_, list_] := (t[[2]] - t[[1]]) Total[list Exp[2 Pi I f list]]

By the way, there is a built-in function for this, Fourier (documentation here), which gives a slightly different DFT than yours but is also useful. I recommend looking for built-in functions for these tasks in the future, because Mathematica has a wide range of functionality like this and will save you a lot of trouble.

Upvotes: 0

Nasser
Nasser

Reputation: 13131

I am guessing you meant you just want to map a function on a column?

mat = RandomInteger[{0, 10}, {5, 6}];
map[f_, mat_?(MatrixQ[#] &), c_Integer /; c > 0] := f /@ mat[[All, c]]

Mathematica graphics

map[f, mat, 2]

Mathematica graphics

Upvotes: 1

Related Questions