Why are these zeros adding themselves to the array?
4 ビュー (過去 30 日間)
古いコメントを表示
clear
clc
function result = expn(x,n)
result = 1;
for i = 1:n
result = (result + x.^i/factorial(i));
end
end
x = [1,-2];
n = [1,2,4,6,10];
ex1 = zeros(1,5);
ex_2 = zeros(1,5);
for k = n
t = expn(x(1),k);
ex1(k) = t;
end
for k = n
t = expn(x(2),k);
ex_2(k) = t;
end
ex1
ex_2
Not sure why the zeros are appearing as elements in the arrays. If someone could help me out it would be much appreciated!
2 件のコメント
採用された回答
Voss
2025 年 2 月 6 日
編集済み: Voss
2025 年 2 月 6 日
k goes 1,2,4,6,10
n = [1,2,4,6,10];
for k = n
fprintf('k = %d\n',k);
end
so inside your loop, e.g., ex1(k) = t; sets ex1(1), ex1(2), ex1(4), ex1(6), ex1(10)
When you set an element of an array that's outside the current size of the array, the array is expanded as necessary with elements containing zeros. So that's where the zeros are coming from.
Example:
vec = zeros(1,5)
vec(4) = 40 % not expanded
vec(10) = 100 % vec gets expanded to length 10 with zeros
You probably meant for ex1 and ex_2 to be length-5 vectors for their entire lifetimes, in which case you'd do something like this:
x = [1,-2];
n = [1,2,4,6,10];
ex1 = zeros(1,5);
ex_2 = zeros(1,5);
m = numel(n);
for k = 1:m
t = expn(x(1),n(k));
ex1(k) = t;
end
for k = 1:m
t = expn(x(2),n(k));
ex_2(k) = t;
end
その他の回答 (2 件)
Walter Roberson
2025 年 2 月 6 日
function result = expn(x,n)
result = 1;
for i = 1:n
result = (result + x.^i/factorial(i));
end
end
x = [1,-2];
n = [1,2,4,6,10];
ex1 = dictionary();
ex_2 = dictionary;
for k = n
t = expn(x(1),k);
ex1(k) = t;
end
for k = n
t = expn(x(2),k);
ex_2(k) = t;
end
ex1
ex_2
0 件のコメント
Catalytic
2025 年 2 月 6 日
ex1=[2.0000 2.5000 0 2.7083 0 2.7181 0 0 0 2.7183]
ex1=nonzeros(ex1)'
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!