Function definition using a variable from a block based on a for loop
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Gábor Dupák
el 22 de Abr. de 2021
Comentada: Gábor Dupák
el 22 de Abr. de 2021
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!
Respuesta aceptada
Steven Lord
el 22 de Abr. de 2021
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
% Approach 2
for k = 1:numel(Att)
y = myf2(Att, A, k);
fprintf("Element %d of the result is %d\n", k, y)
end
function a=myf1(Att, A)
a=Att.*A;
end
function a=myf2(Att, A, ii)
a=Att(ii)*A(ii);
end
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!