Write a MATLAB script to return the vector of powers of a number
6 views (last 30 days)
Show older comments
Hello, I need to write MATLAB script with the function `powers(x, n)`, which will return a vector with first `n˙ powers of number `x`.
4 Comments
Walter Roberson
on 16 May 2025
It is not immediately clear that the results are all correct.
powers(2, 5)
powers(-1, 6)
powers(3, -2.5)
powers(0, 0)
try
powers(3, 4:6)
catch ME
warning(ME.message)
end
try
powers(-1:1, 3)
catch ME
warning(ME.message)
end
function result = powers(x, n)
%POWERS Vrne vektor prvih n potenc števila x
% result = powers(x, n) vrne vektor dolžine n, ki vsebuje x^1, x^2, ..., x^n
result = zeros(1, n); % Inicializacija rezultata
for i = 1:n
result(i) = x^i;
end
end
DGM
on 16 May 2025
I think the suggestion here is that you need to decide how x and n are to be specified -- i.e. whether they're scalars or arrays.
Given the code, I'm going to assume both x and n are strictly scalar, and you only want strictly positive integer powers.
% inputs
x = 2;
n = 8;
% result in one line
y = x.^(1:n)
Of course, you'd have to roll that into a script, but
Answers (1)
Sulaymon Eshkabilov
on 18 May 2025
Maybe to have a few different options embedded in the function file, e.g.:
clearvars
%% Case # 1.
x = [2.2 3:5]; n = [1.5 3 2];
% %% Case # 2.
% x = 5; n = 3;
% %% Case # 3.
% x = 2; n = [2 4 5];
% %% Case # 4.
% x = 2:5; n = 3;
%% Test the cases:
if numel(x)>1 & numel(n)>1 % Case #1.
Result = POWERs(x,n)
elseif numel(x)==1 & numel(n)==1 % Case #2.
Result=x.^(1:n)
elseif numel(x)==1 & numel(n)>1 % Case #3.
Result = x.^(n)
else % numel(x)>1 & nume(n)==1 % Case #4.
Result = POWERs(x,n)
end
function Result = POWERs(x, n)
if numel(x)>1 & numel(n)>1
for ii=1:length(x)
for jj = 1:length(n)
Result(ii, jj)=x(ii)^(n(jj));
end
end
else
for ii=1:length(x)
Result(ii, :)=x(ii).^(1:n);
end
end
end
0 Comments
See Also
Categories
Find more on MATLAB Mobile Fundamentals in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!