create vector in for loop and then need to store vector in a matrix one after another
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Muhammad Asad
el 22 de Abr. de 2022
Comentada: Rik
el 23 de Abr. de 2022
I want to create a code in double for loop shown below. When vector "v" creates in first run then its store values but when internal "for loop" increaed the value of b by 0.1 then previous values in vector v replaced. I need both values and i don,t understand how i get?
Every time value changed i need. I want to store values in a matrix means first run stores in first row, then value increment in internal for loop then this valus agiain stored ina matrix and so on. at the end i need all combinations in a matrix.
Can anyone give me a suitable suggestion? thanks in advance
clear all
for a=1:0.1:2
k1=a
for b=1:0.1:2
k2=b;
v=[k1 k2]
newtable=array2table(v)
end
end
1 comentario
Rik
el 22 de Abr. de 2022
You aren't using any indexing. I suggest you have a look at the relevant chapter of the Onramp tutorial.
Respuesta aceptada
Voss
el 22 de Abr. de 2022
Is this what you mean?
clear all
v = [];
for a=1:0.1:2
k1=a;
for b=1:0.1:2
k2=b;
v(end+1,:)=[k1 k2];
end
end
disp(v);
5 comentarios
Voss
el 22 de Abr. de 2022
The end keyword in an indexing expression refers to the last index of the dimension it's used. So v(end,:) refers to the last row of v, and v(end+1,:) would refer to the row one beyond the last row. In this expression:
v(end+1,:)=[k1 k2 k3]
[k1 k2 k3] is assigned to the row one beyond the last row of v, so the effect is to add a new row to the end of v containing [k1 k2 k3].
About the Simulink block question, I don't know. I've never used Simulink. Maybe ask a new question about it and post the latest version of your code in the new question.
Rik
el 23 de Abr. de 2022
Some comments:
You should avoid clear all. You never actually need it. Using clear or clearvars instead is almost always enough for a debugging script. For actual use, you should be using a function, which will always start out with a clean workspace.
You should try to determine the size of your array based on your variables. That way you can pre-allocate the entire array, which avoids data copying when extending the array, and will also give you an early warning if there are memory issues.
I strongly suggest to do the Onramp tutorial. It is really worth the investment to learn the tool you're using.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!