Matlab交换 [英] Matlab swap

查看:263
本文介绍了Matlab交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数将矩阵中的特定数字与同一矩阵中的特定数字交换.例如,如果我从A = [1 2 3; 1 3 2]开始,我希望能够创建B = [2 1 3; 2 3 1],只需告诉matlab将1与2交换即可.任何意见,将不胜感激.谢谢!

I am trying to create a function that will swap a specific number in a matrix with a specific number in the same matrix. For examlpe, if I start with A = [1 2 3;1 3 2], I want to be able to create B = [2 1 3; 2 3 1], simply by telling matlab to swap the 1's with the 2's. Any advice would be appreciated. Thanks!

推荐答案

处理原始问题的另一种方法是创建一个置换向量,该向量指示原始条目应映射到哪些数字.例如,应将条目[1 2 3]分别映射到[2 1 3],以便我们可以编写

Another way to deal with the original problem is to create a permutation vector indicating to which numbers should the original entries be mapped to. For the example, entries [1 2 3] should be mapped respectively to [2 1 3], so that we can write

A = [1 2 3; 1 3 2];
perm = [2 1 3];
B = perm(A)

(这里的优点是所有步骤都在一个步骤中完成,并且它还可以用于比交换更复杂的操作;缺点是A的所有元素必须是具有已知最大值的正整数)

(advantage here is that everything is done in one step, and that it also works for operations more complicated than swaps ; drawback is that all elements of A must be positive integers with a known maximum)

这篇关于Matlab交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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