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 CenterFile Exchange에서 MATLAB Mobile Fundamentals에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by