How can I create a new vector by passing a function each for loop iteration?

58 vues (au cours des 30 derniers jours)
Hi!
I want to create a new vector after passing a function for every iteration in a for loop. When I pass the function each time, for increasing x, the size of my vector increases.
I've tried doing it by allocating the values in a cell using cellstr, but I really need the individual vectors/ the elements for the rest of my code to work.
Here's the general outline of the function I'm looking to create a loop for,
A0 = function(N);
A1 = function(N-1);
...
Ax = function(N-x);
where for increasing x the function returns a decreasing (1 by something) char vector. I thought it would look something like this,
A = [];
for i=1:x
A(i)=function(N-i+1);
end
I understand why this is wrong, but I'd like some help in generating something to this effect. This is normally a very simple problem in just about every other coding language, except matlab it seems.
Any help would be greatly appreciated, thank you very much!
  1 commentaire
Stephen23
Stephen23 le 16 Oct 2018
"I've tried doing it by allocating the values in a cell using cellstr, but I really need the individual vectors/ the elements for the rest of my code to work."
Only if you want to force yourself into writing slow, complex, buggy code that is hard to debug. Read this to know why your approach is one way that beginners force themselves into writing bad code:
You should learn how to use MATLAB, rather than fighting it with bad code design. The most efficient solution to your task would be to put the data into one array (e.g. cell, structure, table, etc) and use indexing. Indexing is simple, easy to debug, and highly efficient... unlike what you are trying to do.

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 16 Oct 2018
"This is normally a very simple problem in just about every other coding language, except matlab it seems."
It is really simple in MATLAB, you just need to use a cell array:
C = cell(1,x);
for k = 1:x
C{k} = fun(N-k+1);
end
Accessing the data in the cell array is easy, just remember that there are two kinds of indices to access them:

Plus de réponses (1)

KSSV
KSSV le 16 Oct 2018
See this demo code, might help you.
function A = demo()
m = 2 ; n = 3 ;
A = zeros(m,n) ;
for i = 1:m
for j = 1:n
A(i,j) = myfun(i,j) ;
end
end
end
function R = myfun(a,b)
R = a+b ;
end
  1 commentaire
Dipie11
Dipie11 le 16 Oct 2018
I see what you've done, thank you. The size of my vectors change with each iteration though, so I can't store them in a matrix, it would be nice to have each individual vector for each call of the function in the loop.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by