2

I want a code the below code more efficient timewise. preferably without a loop.

arguments:

t % time values vector
t_index = c % one of the possible indices ranging from 1:length(t).
A % a MXN array where M = length(t)
B % a 1XN array

code:

m = 1;
for k = t_index:length(t)
        A(k,1:(end-m+1)) = A(k,1:(end-m+1)) + B(m:end); 
        m = m + 1;
end 

Many thanks.

0

1 Answer 1

2

I'd built from B a matrix of size NxM (call it B2), with zeros in the right places and a triangular from according to the conditions and then all you need to do is A+B2.

something like this:

N=size(A,2);
B2=zeros(size(A));
k=c:length(t);
B2(k(1):k(N),:)=hankel(B)
ans=A+B2;

Note, the fact that it is "vectorized" doesn't mean it is faster these days. Matlab's JIT makes for loops comparable and sometimes faster than built-in vectorized options.

Sign up to request clarification or add additional context in comments.

3 Comments

I had a similar solution but I deleted it, I couldn't get it quite right :) Not to mention that I got out-of-memory errors from the hankel function with the sizes the OP was using
I'm not sure this is better than the for loop in performance at all. Why would the hankel get you out of memory?
actually a for loop does a better job on my computer... Many thanks anyways, i've still learned quite alot from the experience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.