【问题标题】:Matlab: Looping through an arrayMatlab:循环遍历数组
【发布时间】:2015-06-15 17:39:57
【问题描述】:

这是我的一维数组A。包含10个数字

A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
     -2.57400000000000 -4.52700000000000 9.63300000000000 ...
     4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];

我希望循环像这样通过; (计算平均区间) - 区间长度为 2,4,8

  1. (a(1)+a(2))/2 - 存储在一个矩阵块中的值说 m= zeros(10)
  2. 然后(a(1)+a(2)+a(3)+a(4))/4 ------ 意思是-----
  3. 然后(a(1)+a(2)..... a(8))/8

然后移位索引;

  1. (a(2)+a(3))/2; - 意思是
  2. (a(2)+a(3)+a(4)+a(5))/4
  3. (a(2)+a(3)...a(9))/8

所以基本上是 2^n 长度区间

【问题讨论】:

  • 总共会有 19 个平均值。
  • 还有标准差和协方差!这些间隔中的
  • 我现在有一个 64x256 矩阵。我需要分别计算第一行的 mean_2,然后是第二行,所以现在,im2col 似乎在列下,我希望它按行计算?

标签: matlab loops for-loop while-loop do-while


【解决方案1】:

您可以使用conv 来完成此操作,而无需循环

avg_2 = mean([A(1:end-1);A(2:end)])

avg_4 = conv(A,ones(1,4)/4,'valid')

avg_8 = conv(A,ones(1,8)/8,'valid')

样本输入的输出:

avg_2 =
0.8445    5.9715   -0.6205   -3.5505    2.5530    6.9475   10.6100   12.5635    6.4600

avg_4 =
0.1120    1.2105    0.9662    1.6985    6.5815    9.7555    8.5350

avg_8 =
3.3467    5.4830    4.7506

查找标准偏差示例 (std_4)

%// each 1x4 sliding sub-matrix is made a column
%// for eg:- if A is 1x6 you would get 1-2-3-4, 2-3-4-5, 3-4-5-6 each as a column
%// ending with 3 columns. for 1x10 matrix, you would get 7 columns
reshaped_4 = im2col(A,[1 4],'sliding');    %// change 4 to 2 or 8 for other examples

%// calculating the mean of every column
mean_4 = mean(reshaped_4);

%// Subtract each value of the column with the mean value of corresponding column
out1 = bsxfun(@minus,reshaped_4,mean_4);

%// finally element-wise squaring, mean of each column 
%// and then element-wise sqrt to get the output.
std_4 = sqrt(mean(out1.^2))

样本输入的输出:

std_4 =

7.0801    5.8225    5.4304    5.6245    7.8384    4.5985    5.0906

OP 的完整代码

clc;
clear;
close all;

A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
     -2.57400000000000 -4.52700000000000 9.63300000000000 ...
     4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];

reshaped_2 = im2col(A,[1 2],'sliding'); %// Length Two 
mean_2 = mean(reshaped_2); 
out1 = bsxfun(@minus,reshaped_2,mean_2); 
std_2 = sqrt(mean(out1.^2)) 
reshaped_4 = im2col(A,[1 4],'sliding'); %// Four 
mean_4 = mean(reshaped_4); 
out1 = bsxfun(@minus,reshaped_4,mean_4); 
std_4 = sqrt(mean(out1.^2)) 
reshaped_8 = im2col(A,[1 8],'sliding'); %// Eight 
mean_8 = mean(reshaped_8); 
out1 = bsxfun(@minus,reshaped_8,mean_8); 
std_8 = sqrt(mean(out1.^2))

【讨论】:

  • 下标索引必须是正整数或逻辑数。 - 错误?
  • 如果我有多行数字,我需要一个循环吗?
  • @HarshSharma conv2 用于二维数组,convn 用于多维数组。你不需要循环!! ;)
  • @HarshSharma 哈哈!有关更多示例,请参阅this BTW,如果您觉得此答案有帮助,请考虑接受此答案
  • @HarshSharma - conv 实际上用于多项式乘法。这是它最常见的用途之一,所以你是对的。
猜你喜欢
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多