필터 지우기
필터 지우기

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

조회 수: 7 (최근 30일)
Li Xue
Li Xue 2016년 2월 11일
댓글: Guillaume 2016년 2월 11일
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);

채택된 답변

Guillaume
Guillaume 2016년 2월 11일
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
Li Xue
Li Xue 2016년 2월 11일
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 2016년 2월 11일
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))

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by