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

19 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2018-10-16
"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.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2018-10-16
"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:

更多回答(1 个)

KSSV
KSSV 2018-10-16
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 个评论
Dipie11
Dipie11 2018-10-16
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by