Function definition using a variable from a block based on a for loop

4 ビュー (過去 30 日間)
Gábor Dupák
Gábor Dupák 2021 年 4 月 22 日
コメント済み: Gábor Dupák 2021 年 4 月 22 日
Hi!
I would like to create a function in which the definition changes according to a for loop.
I have 2 row vectors from which I want to use values:
A=[1 2 3 4 5 6 7 8 9 10]
Att=[0 2 4 6 8 10 12 14 16 18]
An example:
function [a]=myf(Att)
a=Att(ii)*A(ii);
end
I would like to use the first elements of A and Att in the first cycle then the second and so on. My real function is a bit more complicated, my question is how can I change the variable inside the function according to a for loop.
Thank you!
  1 件のコメント
Gábor Dupák
Gábor Dupák 2021 年 4 月 22 日
Oh and I know that it can be solved without using a function, but I MUST use a function ! :)

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

採用された回答

Steven Lord
Steven Lord 2021 年 4 月 22 日
For this I'd use one of two approaches.
A=[1 2 3 4 5 6 7 8 9 10];
Att=[0 2 4 6 8 10 12 14 16 18];
% Approach 1
y = myf1(Att, A);
for k = 1:numel(Att)
fprintf("Element %d of the result is %d\n", k, y(k))
end
Element 1 of the result is 0 Element 2 of the result is 4 Element 3 of the result is 12 Element 4 of the result is 24 Element 5 of the result is 40 Element 6 of the result is 60 Element 7 of the result is 84 Element 8 of the result is 112 Element 9 of the result is 144 Element 10 of the result is 180
% Approach 2
for k = 1:numel(Att)
y = myf2(Att, A, k);
fprintf("Element %d of the result is %d\n", k, y)
end
Element 1 of the result is 0 Element 2 of the result is 4 Element 3 of the result is 12 Element 4 of the result is 24 Element 5 of the result is 40 Element 6 of the result is 60 Element 7 of the result is 84 Element 8 of the result is 112 Element 9 of the result is 144 Element 10 of the result is 180
function a=myf1(Att, A)
a=Att.*A;
end
function a=myf2(Att, A, ii)
a=Att(ii)*A(ii);
end
  2 件のコメント
Gábor Dupák
Gábor Dupák 2021 年 4 月 22 日
Thank you! And how I can store the results in a row vector? It would be very helpful for me :)
Gábor Dupák
Gábor Dupák 2021 年 4 月 22 日
Oh I solved it ! Your help was awesome !

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by