user466534
user466534

Reputation:

calculation of value from given matrix

suppose that we have following array :

a=[12 21 23 10 34 54 10 9 5 6 7 8]

a =

    12    21    23    10    34    54    10     9     5     6     7     8

length(a)=

length(a)

ans =

    12

now i want to create following vector b ,which b(1),b(2)...b(6) are following

b(1)=sqrt(a(1)^2+a(2)^2)
 b(2)=sqrt(a(3)^2+a(4)^2)

 b(3)=sqrt(a(5)^2+a(6)^2))
 b(4)=sqrt(a(7)^2+a(8)^2)
  b(5)=sqrt(a(9)^2+a(10)^2))
 b(6)=sqrt(a(11)^2+a(12)^2)

i have wrote following code

or i=2:2:length(a)
   b(i/2)=sqrt(a(i-1)^2+a(i)^2);
end
>> b

b =

   24.1868   25.0799   63.8122   13.4536    7.8102   10.6301

but i am not sure if it is correct,pleas help me to clarify if everything is ok in my code

Upvotes: 0

Views: 51

Answers (1)

vipers36
vipers36

Reputation: 300

In matlab, loops are quite slow. Using vectors is much faster. I suggest therefore a solution without a loop:

a_1 = a(1:2:end);
a_2 = a(2:2:end);

b = sqrt(a_1.^2 + a_2.^2);

first, you create a vector a_1 containing all elements with odd indices of a and a vector a_2 containing all elements with even indices. Then you square them element wise (.^) and take the square of the sum. For you example of a, this is 75 times faster. As you increase the size of the array, you will save even more time.

Upvotes: 2

Related Questions