Write a MATLAB script to return the vector of powers of a number

6 ビュー (過去 30 日間)
andrej
andrej 2025 年 5 月 16 日
回答済み: Sulaymon Eshkabilov 2025 年 5 月 18 日
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 件のコメント
Walter Roberson
Walter Roberson 2025 年 5 月 16 日
It is not immediately clear that the results are all correct.
powers(2, 5)
ans = 1×5
2 4 8 16 32
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
powers(-1, 6)
ans = 1×6
-1 1 -1 1 -1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
powers(3, -2.5)
ans = 1×0 empty double row vector
powers(0, 0)
ans = 1×0 empty double row vector
try
powers(3, 4:6)
catch ME
warning(ME.message)
end
Warning: Size inputs must be scalar.
try
powers(-1:1, 3)
catch ME
warning(ME.message)
end
Warning: Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To operate on each element of the matrix individually, use POWER (.^) for elementwise power.
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
DGM 2025 年 5 月 16 日
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)
y = 1×8
2 4 8 16 32 64 128 256
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Of course, you'd have to roll that into a script, but

サインインしてコメントする。

回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2025 年 5 月 18 日
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
Result = 4×3
3.2631 10.6480 4.8400 5.1962 27.0000 9.0000 8.0000 64.0000 16.0000 11.1803 125.0000 25.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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

カテゴリ

Help Center および File ExchangeMATLAB Mobile Fundamentals についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by