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
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
2018-10-16
"This is normally a very simple problem in just about every other coding language, except matlab it seems."
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:
0 个评论
更多回答(1 个)
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!