how to return an output with more than one column/row
6 ビュー (過去 30 日間)
古いコメントを表示
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);
0 件のコメント
採用された回答
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 件のコメント
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 Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!