How to enforce element-wise condition in matrix operations?
2 次查看(过去 30 天)
显示 更早的评论
I am trying to use \ for Euler's backward method:
where dt and lambda are constant numbers like:
dt = 0.01
lambda = 0.5
and L is a square matrix with the same size as x_old and x_new
here is what I have tried:
x_new = (speye(size(x_old,2))- dt * lambda * L) \ x_old;
I had two questions:
- How to avoid the division in the elements of L that are 0?
- Is it OK to move (speye(size(x_old,2))- dt * lambda * L) to the other side, or should I maintain the formula's structure?
For the first question, I tried this but didn't work:
x_new = (speye(size(x_old,2))- dt * lambda * L(L~=0)) \ x_old;
2 个评论
Guillaume
2019-11-24
I'm unclear why you want to ignore the 0s in L and why you think they don't matter. Note that \ is not a division, it's a linear equation solver and 0s do matter for a linear equation.
In any case, it's not possible to remove the 0s. You have to pass a matrix to \. You can remove entire rows or colums but you can't have matrix cells with nothing in them.
Also, are you matrix so large that you have to use sparse matrix? Otherwise, I would be better defined as eye(size(x_old)). Even if using speye, I would use speye(size(x_old)) instead of speye(size(x_old, 2)). The two are equivalent iff x_old is square but the former is more consise (and probably inifinitesimally faster).
采纳的回答
Guillaume
2019-11-24
Reposting my comment as an answer and adding a bit more to it.
I'm unclear why you want to ignore the 0s in L and why you think they don't matter. Note that \ is not a division, it's a linear equation solver and 0s do matter for a linear equation.
In any case, it's not possible to remove the 0s. You have to pass a matrix to \. You can remove entire rows or colums but you can't have matrix cells with nothing in them.
Also, are you matrix so large that you have to use sparse matrix? Otherwise, I would be better defined as eye(size(x_old)). Even if using speye, I would use speye(size(x_old)) instead of speye(size(x_old, 2)). The two are equivalent iff x_old is square but the former is more consise (and probably inifinitesimally faster).
"should I use .*"
Your multiplications are with scalars, so using .* or * doesn't make a difference
"should I use .\"
That's a completely different operation. If you are trying to solve linear equations you have to use \
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!