Can anyone here help me with making a matlab function, it's an exercise yes, but I don't really know much of recursions.
Here's what I have to do:
Given two integers, write a function, recursiveProduct, that calculates the product of the two numbers.
You *must* use recursion.
You may *not* use the * or .* operators.
You may *not* use the prod() function.
You MAY assume that the second integer will not be negative
>>3
As a matter of fact, >>2 did help you. There's an answer in SICP, with a nice chart and all (be sure to read the errata, there's an error in the chart!).
The real answer is that you've been given the answer thrice — one in algorithmic form (>>2), one in a language you should know (>>4), and heck, even one in a toy language if you're into that (>>8). If you can't turn that into an algorithm in any language, then perhaps it's time to find a new hobby.
Easy enough, except I don't know matlab, so here's a CL solution:
(defun multiply (x y)
(case y
(0 0) (1 x) (-1 (- x))
(t (+ (if (zerop (logand y 1)) 0 x)
(multiply
(ash x 1)
(ash y -1))))))
Works with negative numbers too (or any fixnum/bignums).
Add a local function for accumulating the results if you want to accumulate the result (take advantage of TCO).
I believe an iterative solution would be fine here too.
Here's a simple C solution too (much shorter since C has special syntax for shifts/arith ops):
int multiply(int x, unsigned int y)
{
int product;
for (product=0;y;x<<=1,y>>=1)
if (y&1) product+=x;
return product;
}
I was going to write a x86 assembly version too, but looking at the compiled version of the previous function, I decided against it (it was good enough):
;; the body of the function taking 2 arguments, cdecl convention
mov ecx, dword ptr [esp+8]
xor eax, eax
test ecx, ecx
jz done
mov edx,[esp+4]
I could probably write a VHDL implementation of it too, since that's usually a common part of an ALU, and most of the time the only sensible place you want to implement this (why bother when most CPUs and languages have multiply instructions provided for you? They are much more efficient because they're implemented in hardware, and in cases when you're multiplying by a constant, the compiler can just optimize it all into shifts/adds).