MATLAB: How to return an output with more than one column/row

rowfun

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);

Best Answer

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.