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

14 visualizzazioni (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 16 Ott 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.

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 16 Ott 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:

Più risposte (1)

KSSV
KSSV il 16 Ott 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 Commento
Dipie11
Dipie11 il 16 Ott 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.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by