【问题标题】:How to replace values in specific lines and on determined conditions如何在特定行和确定的条件下替换值
【发布时间】:2017-07-06 23:33:50
【问题描述】:

我遇到了麻烦:我有一个包含 128597 行和 10 列的数据集。 我需要在第 10276 行到 128597 之间更改第 10 列的值。

而且这种变化必须遵守一些条件,例如: 如果值在 11 到 33 之间,则该值将变为 1 如果值在 34 和 56 之间,则该值将变为 5 继续……

我尝试了下面的代码,但没有成功:

m(10276:128597,10) > 11 & m(10276:128597,10)

谁能帮帮我!!! :)

【问题讨论】:

  • 这样,您只能获得索引作为逻辑输出。我认为你应该这样做: m(m(10276:128597,10) > 11 & m(10276:128597,10)
  • 嗨,约翰。你说的我试过了,还是不行。
  • 没有用是什么意思?输出是什么样的?
  • 我查看了数据,值没有变化。
  • 其实你是对的,它不起作用。我会仔细测试的

标签: matlab if-statement replace find conditional


【解决方案1】:

我认为这可能会有所帮助

a=[1,2,3;2,3,4;3,2,1;2,4,1];
amask=false(size(a));
amask(2:3,3)= a(2:3,3)>3;
a(amask)=9999;

答案是

一个=

 1     2     3
 2     3     4
 3     2     1
 2     4     1

一个=

       1           2           3
       2           3        9999
       3           2           1
       2           4           1    

【讨论】:

    【解决方案2】:

    如果您的分类是连续的,即类别之间没有间隙,您可以使用discretize。像这样,您可以一次更改所有值,并且如果您有很多 if bins,则不必使用大量逻辑运算符。

    % edges of the bins. As an example there are currently 3 bins ranging from
    % 11 to 34, 34 to 57, 57 to 77. The upper values are included in the next bin, i.e. bin 2 goes from 34.0 to 56.999999
    edges = [11 34 57 77];
    % Example values you want to give to the bins. Length has to be one shorter than edges
    replacementvalues = [1 5 9];
    
    % subset of the data you want to change
    subset = m(10276:128597,:);
    % bin the subset into categories
    binnumber = discretize(subset,edges);
    % replace the values in subset that are inside those bins
    subset(~isnan(binnumber)) = replacementvalues(binnumber(~isnan(binnumber)));
    % replace the values in the original matrix with the updated subset
    m(10276:128597,:) = subset;
    

    如果箱之间有间隙,可以通过制作第二组“不更改”箱来扩展代码。

    【讨论】:

      猜你喜欢
      • 2016-06-20
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 2022-12-18
      相关资源
      最近更新 更多