Nick
Nick

Reputation: 1116

Huge number of intilization a small vector without a for-loop?

I received the code to the initialization the vector A1.

Sc=[75 80 85];
Sp=[60 65 70];
C=[10 20 30 40 50 60;
   11 21 31 41 51 61];
% KK=1000000;
%    for k=1:KK

k=1;
    A1=[];
    A1=[-C(k,1)+max(60-Sc(1),0) -C(k,2)+max(60-Sc(2),0) -C(k,3)+max(60-Sc(3),0) 
        -C(k,4)+max(Sp(1)-60,0) -C(k,5)+max(Sp(2)-60,0) -C(k,6)+max(Sp(3)-60,0)];
%end; %KK

The code above is work, but it isn't optimal (it's very long and I need rewrite it when vector's length, n, is changed). In my task the length of A1 is even, and lies in range 6<=n<=16 typically. But I need to initialize vector A1 the huge number times, k<=10^6. I'd like to rewrite code. My code is below.

    n= size(C,2);
M=60;
%KK=1000000;
%    for k=1:KK
k=1;

    AU=[];AD=[];
    for i=1:n 
    if i<=n/2
    AU=[AU, -C(k,i)+max(M-Sc(i),0)];
    else
    AD=[AD, -C(k,i)+max(Sp(i-n/2)-M,0)];
    end %if
    end % i
    A1=[AU; AD]
%    end; % KK

Question. Is it possible to rewrite the code without for-loop? Does it make sense when the vector's length, n, is substantially less the number of initialization, k?

Upvotes: 0

Views: 42

Answers (1)

rahnema1
rahnema1

Reputation: 15867

This is a vectorized form:

Sc=[75 80 85];
Sp=[60 65 70];
C=[10 20 30 40 50 60;
   11 21 31 41 51 61];
kk=2;%1000000;
n= 6;
M=60;
[K , I] = meshgrid(1:kk,1:n);
Idx = sub2ind([kk,n], K, I);
condition = I <= n/2;

AU = -C(Idx(condition)) + max(M-Sc(I(condition)),0).';
AD = -C(Idx(~condition)) + max(Sp(I(~condition) - n/2)-M,0).';
A1 = [AU AD].'

note: I changed kk from 1000000 to 2 because number of rows of C is 2 and can not be indexed with numbers greater than 2. So this make sence if number of rows of C would be 1000000

Upvotes: 2

Related Questions