开发者

generate a name vector MATLAB

开发者 https://www.devze.com 2023-02-16 03:28 出处:网络
How would I generate a vector like x1,x2,x3,x4,...,xn the problem is concatenate \',\'and a \'x\' char

How would I generate a vector like

x1,x2,x3,x4,...,xn 

the problem is concatenate ','and a 'x' char

n=开发者_如何学运维100
A = (1:n);


This is a slight improvement on @Jonas's answer. SPRINTF will do the repeating for you avoiding the need for a mask:

>> n = 5;
>> out = sprintf('x%u,', 1:n);
>> out(end) = []

out =

x1,x2,x3,x4,x5


To generate the string 'x1,x2' etc, you can create a mask for SPRINTF using REPMAT like so:

n = 5;

mask = repmat('x%i,',1,n);

out = sprintf(mask,1:n);

out = out(1:end-1)

out =
x1,x2,x3,x4,x5

Note that in case you actually want to create a vector containing the strings 'x1','x2' etc, you'd use ARRAYFUN to generate a cell array:

out = arrayfun(@(x)sprintf('x%i',x),1:n,'uniformOutput',false)
out = 
    'x1'    'x2'    'x3'    'x4'    'x5'


The better answer is, don't do it. While you CAN do so, this will likely cause more heartache for you in the future than you want. Having hundreds of such variables floating around is silly, when you can use an array to index the same data. Thus perhaps x{1}, x{2}, ....

0

精彩评论

暂无评论...
验证码 换一张
取 消