How can I create a new vector by passing a function each for loop iteration?
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dipie11
am 16 Okt. 2018
Kommentiert: Stephen23
am 16 Okt. 2018
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 Kommentar
Stephen23
am 16 Okt. 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.
Akzeptierte Antwort
Stephen23
am 16 Okt. 2018
"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 Kommentare
Weitere Antworten (1)
KSSV
am 16 Okt. 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
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!