在Matlab中对向量施加限制 [英] forcing limits on a vector in matlab

查看:237
本文介绍了在Matlab中对向量施加限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题: 假设我有一个矩阵

I have a problem : suppose I have a matrix

A =

    -1     2    -3
    -4     5    -6
    -7     8    -9

我将其转换为列矩阵

B = A(:)

B =

    -1
    -4
    -7
     2
     5
     8
    -3
    -6
    -9  

假设我要强制第一列元素位于特定范围(-range1:range1)内,第二列元素位于(-range2:range2)&中; (-range3:range3)中的第三列元素.我尝试通过实现以下代码来做到这一点:

Suppose I want to force the first column elements to lie within a particular range (-range1 : range1) , second column elements within (-range2 : range2) & third column elements within (-range3:range3). I tried doing that by implementing this code :

range1 = 0;
range2 = -5;
range3 = 0;

B(B(1:3,1)<range1)=10;
B(B(4:6,1)>range2)=0;
B(B(7:9,1)<range3)=20;

我得到的答案是:

B =

    20
    20
    20
     2
     5
     8
    -3
    -6
    -9

我应该得到的正确答案是:

Whereas the correct answer I should get is this :

B =

    10
    10
    10
     0
     0
     0
    20
    20
    20

我做错了什么?请帮忙.

What I am doing wrong ? Please help.

推荐答案

出了什么问题:

仔细查看您的命令:

What is wrong:

Look closely at your command:

>> B( B(7:9, 1) < range3 ) = 20;

现在让我们逐步进行

您要以最后三个元素B( 7:9, 1 )为条件,这些元素分别是-3, -6-9.
因此,您最终会得到

You are conditioning on the last three elements B( 7:9, 1 ) which are -3, -6 and -9.
Therefore you end up with

>> B(7:9, 1) < range3
ans = 
  true
  true 
  true

您有三个元素的逻辑索引.使用这些逻辑索引来访问具有 9 个元素的B,从而可以访问九个中的前三个元素.
因此,您的所有命令仅修改B的前三个元素,而不会影响B的其余部分.

You have a logical indexing of three elements. Using these logical indices to access B, which has 9 elements result with an access to the first three elements out of nine.
Thus, all your commands only modifes the first three elements of B without affecting the rest of B.

您可以主动定义要处理的范围,例如第二列:

You can actively define the range you are working on, for example, the second column:

>> aRange = 4:6;
>> B( aRange( B(aRange, 1) > range2 ) ) = 0

看看三向量逻辑索引B(aRange, 1) > range2 )现在如何直接索引aRange(具有3个元素)而不是B(具有9个元素).

See how the three-vector logical indexing B(aRange, 1) > range2 ) now index aRange (which has 3 elements) and not B (which has 9 elements) directly.

这篇关于在Matlab中对向量施加限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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