Hi,
I'm dealing with a sparse array. Given 2 arrays "col" and "val", I want to create a one-rowed sparse array of value val(i) in the column col(i), for all i.
What I did is:
if true
% val, col given
leng = length(val);
row = ones(1, leng);
result = sparse(row, col, val, 1, leng);
end
Is there a better way to do, without creating an array "row" in particular? Because getting the length and creating the row take a bit of time in my problem.
Thanks!

 채택된 답변

Walter Roberson
Walter Roberson 2013년 11월 13일

1 개 추천

result = sparse(1, col, val);
Note: this is not exactly equivalent to what you wrote. What you wrote only allocates a 1 x leng array, but leng is the number of elements in col, not the maximum col.
For example, sparse(1, 10, 3, 1, 1) would try to create a 1 x 1 sparse matrix, but it needs a 1 x 10 sparse matrix.

댓글 수: 4

Sorry, I made a mistake. I want to create an array whose width I know, say nCol.
In particular I have max(col) < nCol.
The line I really wrote in Matlab is
result = sparse(row, col, val, 1, nCol);
I wil try sparse(1, col, val, 1, nCol). Thanks for your answer anyway.
Martin
Martin 2013년 11월 15일
It works :), thanks Walter! It's faster.
Walter Roberson
Walter Roberson 2013년 11월 15일
Much faster or just "faster" ?
Martin
Martin 2013년 11월 18일
In my program, the time necessary to create the matrix itself is similar, but I saved the time to create the "row" array. In particular, calculating the length of this array took time.
I'd say I saved about 25% of time but I reckon this is very problem-specific.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Sparse Matrices에 대해 자세히 알아보기

질문:

2013년 11월 12일

댓글:

2013년 11월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by