简体   繁体   English

如何在Matlab中向向量添加元素

[英]How to add elements to a vector in matlab

I've looked around on the internet a bit and cannot seem to find the answer to this question. 我在互联网上四处张望,似乎找不到这个问题的答案。 I want to declare a vector in matlab and then have a for loop that will add an element to the vector each time I go through the for loop. 我想在matlab中声明一个向量,然后有一个for循环,每次我通过for循环时,都会向向量中添加一个元素。

This is what I've tried and it doesn't seem to be working 这是我尝试过的方法,似乎没有用

vector[];

for k = 1 ; 10
%calculate some value
%calculated value stored in temp variable
vector(k) = temp;
end

This does not work. 这是行不通的。 Does anybody know how to solve this issue? 有人知道如何解决这个问题吗?

As ypnos said, you don't need to declare the vector variable upfront. 正如ypnos所说,您不需要预先声明向量变量。 For example if you did: 例如,如果您这样做:

vector(50) = 1;

MATLAB would make a vector of length 50 with the 50th value being 1. If you want to improve performance and want to create a vector of the proper size beforehand then do the following: MATLAB会制作一个长度为50的向量,第50个值为1。如果要提高性能并希望事先创建适当大小的向量,请执行以下操作:

vector = zeros(10, 1);

The code as you have it (as long as you fix the loop as ypnos said) will work, except for how you declare vector, which is not correct. 您所拥有的代码(只要按照ypnos所述修复了循环)就可以了,除了声明向量的方式不正确外。 I bet you are getting the error message: "Error: Unbalanced or unexpected parenthesis or bracket." 我敢打赌,您会收到错误消息: "Error: Unbalanced or unexpected parenthesis or bracket." You do not specify whether a variable is a matrix/vector in MATLAB. 您未在MATLAB中指定变量是否为矩阵/向量。

vector = [vector; temp];

要么

vector(end+1) = temp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM