It's hard to know quite where to start with this, but I'd start with the answers to this question for some initial guidance.
As a general guide, nested For
loops are almost never necessary and using list-based operations is much more efficient, as well as readable and less prone to error.
Let's take the inner loop first.
For[h = 1, h <= 3, h = h + 1,
x = a [[1, h]];
y22 = x^j-2;
y1 = Append[y1, y22]; ];
All you are really doing is constructing a vector of each element of a
(respecifying a
as a vector {3, 5, 2}
) taken to the power j
and then subtracting 2. By the way, is that what you want? or did you mean x^(j-2)
?
So eliminate this loop by using the Listable
property of arithmetic operations and writing
a^j - 2
You can eliminate most of the outer loop by changing this to
a^# - 2 & /@ Range[10]
Where Range[10]
is what I think your definition of k
in your Matlab code does. Evaluate that and check.
The result of the last line above is:
{{1, 3, 0}, {7, 23, 2}, {25, 123, 6}, {79, 623, 14}, {241, 3123,
30}, {727, 15623, 62}, {2185, 78123, 126}, {6559, 390623,
254}, {19681, 1953123, 510}, {59047, 9765623, 1022}}
(Incidentally Outer[#2^#1 - 2 &, Range[10], a]
gives the same output. You might want to experiment with some other list-based functions.)
You want the minimum of each row of that, so just use Map
(shortcut notation /@
) like this
Min /@ ( a^# - 2 & /@ Range[10])
And your result should be
{0, 2, 6, 14, 30, 62, 126, 254, 510, 1022}
Yes, all you need to replace that convoluted nested For
loop is:
a = {3, 5, 2};
Min /@ ( a^# - 2 & /@ Range[10])
ListLinePlot@Table[Min[{3, 5, 2}^j - 2], {j, 10}]
?? But as written you can substituteMin[]
for just2^j-2
... $\endgroup$minfind
andy1
as empty lists. $\endgroup$