Azzera filtri
Azzera filtri

how to return an output with more than one column/row

7 visualizzazioni (ultimi 30 giorni)
I want to process each row of a table by a function like [i,j]=f(row). Here is an example, where I am trying to return a sparse matrix:
A=table([ 11 90 -0.023]);
B=rowfun(@myfun,A )
function S=myfun(x)
data1=[90 1290 11 89];
data2=[23 90 12 0];
i=find(data1==x(1));
j=find(data2==x(2));
value=x(3);
S=sparse(i,j, value);

Risposta accettata

Guillaume
Guillaume il 11 Feb 2016
Just add 'OutputFormat', 'cell' to your rowfun call and it will work. If you want to convert the output cell array to a table you can do that afterward:
A = table([11 90 -0.023; 89 23 0.005]);
myfun = @(x) sparse(find(x(1) == [90 1290 11 89]), find(x(2) == [23 90 12 0]), x(3));
B = rowfun(myfun, A, 'OutputFormat', 'cell');
%and if you want a table in the end:
B = table(B);
But:
1. Did you really mean to create a 1 column table rather than a 3 column table that you'd obtain with:
A = array2table([11 90 -0.023; 89 23 0.005])
Note that if you use a 3 column table, you'll have to modify the rowfun call (or the processing function):
%modify rowfun:
B = rowfun(myfun, A, 'OutputFormat', 'cell', 'SeparateInputs', false)
%or modify function
myfun = @(i, j, v) sparse(find(i == [90 1290 11 89]), find(j == [23 90 12 0]), v);
B = rowfun(myfun, A, 'OutputFormat', 'cell')
2. Do you really want an output that's going to vary in size. Shouldn't you specify the size of output matrix in sparse?
3. What is the end goal here? There may be a much simpler way of obtaining what you want.
  2 Commenti
Li Xue
Li Xue il 11 Feb 2016
Dear Guillaume, many thanks for your help.
The first two columns of A are indices, and the 3rd column is value. The end goal is to convert original indices in A to new indices (using data1 and data2), and save the new indices and value into a sparse matrix.
Guillaume
Guillaume il 11 Feb 2016
Note, as per my point 1, A is only one column (with 3 values). You'd have to use array2table instead of table to create a table with 3 columns.
Anyway, there's a much simpler way to create that sparse matrix:
m = [ 11 90 -0.023
90 0 -0.005
89 12 0.714
1290 23 1.856
11 12 3.141]; %not bothering with table
newroworder = [90 1290 11 89];
newcolorder = [23 90 12 0];
[~, newrow] = ismember(m(:, 1), newroworder);
[~, newcol] = ismember(m(:, 2), newcolorder);
s = sparse(newrow, newcol, m(:, 3))

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Tables in Help Center e File Exchange

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by