如何在工作区中创建序列编号的变量? [英] How to create serially numbered variables in workspace?

查看:108
本文介绍了如何在工作区中创建序列编号的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在给定一定数量的情况下如何使用for循环创建多个矩阵.

I was wondering how I can use a for loop to create multiple matrix when given a certain number.

就像给定3一样,我需要三个矩阵:C1,C2和C3.

Such as If 3 was given I would need three matricies called: C1, C2 and C3.

k = 3
for i = 1:K
    C... = [ ]
end

不确定如何实现.

推荐答案

首先要想到的是Dennis Jaheruddin提到的eval函数,是的,这是一种不好的做法. 文档也这样说:

The first thing coming in mind is the eval function mentioned by Dennis Jaheruddin, and yes, it is bad practice. So does the documentation say:

为什么要避免使用eval函数?

尽管eval功能非常强大和灵活,但它不 始终是编程问题的最佳解决方案.调用的代码 与eval相比,eval通常效率较低,并且更难以阅读和调试 使用其他功能或语言结构的代码.例如:

Although the eval function is very powerful and flexible, it not always the best solution to a programming problem. Code that calls eval is often less efficient and more difficult to read and debug than code that uses other functions or language constructs. For example:

MATLAB®首次运行时会编译代码,以增强以后运行的性能.但是,因为代码在评估中 语句可以在运行时更改,无法编译.

MATLAB® compiles code the first time you run it to enhance performance for future runs. However, because code in an eval statement can change at run time, it is not compiled.

eval语句中的代码可能会意外地创建或分配给当前工作空间中已经存在的变量,从而覆盖现有变量 数据.

Code within an eval statement can unexpectedly create or assign to a variable already in the current workspace, overwriting existing data.

在eval语句中连接字符串通常很难读取.其他语言构造可以简化您的语法 代码.

Concatenating strings within an eval statement is often difficult to read. Other language constructs can simplify the syntax in your code.

更安全"的替代方法是功能 assignin :

The "safer" alternative is the function assignin:

以下内容将完全满足您的要求:

The following will do exactly what you want:

letter = 'C';
numbers = 1:3;

arrayfun(@(x) assignin('base',[letter num2str(x)],[]),numbers)

我知道您需要创建这样的变量的情况,但是在大多数情况下,使用单元格数组结构会更好,更方便.

I know cases where you need to create variables likes this, but in most cases it is better and more convenient to use cell arrays or structs.

这篇关于如何在工作区中创建序列编号的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆