I have a set of code that works, but a part of it runs very slowly. Basically I'm trying to remove zero-only rows from two matrixes, and I'm able to tell that both have an empty row if the first element in one matrix is zero. Here's the actual code:
for a=1:numberofrows
if slopes(a,1)==0
slopes(a,:)=[];
switchingtimes(a,:)=[];
end
end
I'd try to do a nonzeros function and then a reshape function, but sometimes slopes have a zero or two at the end of a column.
Is there any way to speed up this code?

 채택된 답변

Geoff Hayes
Geoff Hayes 2019년 3월 1일

1 개 추천

Christian - what about using find as
slopes(find(slopes(:,1)==0), :) = []
We use find to return all indices of the first column of slopes whose element is a zero. We then remove all of these rows with the assignment to [] (like you have done already).

댓글 수: 2

Christian F
Christian F 2019년 3월 4일
Thanks! It worked way faster than the old code!
Stephen23
Stephen23 2019년 3월 4일
편집: Stephen23 2019년 3월 4일
find is not required. Logical indexing is simpler and faster:
idx = slopes(:,1)==0;
slopes(idx,:) = []
switchingtimes(idx,:) = [];

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

추가 답변 (0개)

카테고리

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

제품

릴리스

R2018b

질문:

2019년 3월 1일

편집:

2019년 3월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by