for循环在每次迭代中打印相同的东西,应该只打印一次

时间:2017-07-06 21:10:18

标签: matlab for-loop

我遇到麻烦,我的for循环从17个元素打印相同的向量17次而不是打印1次并从17个元素中绘制。出了什么问题?

另外,我试图在倒置矢量的末尾添加平均值,但是它说尺寸是关闭的。 (第二个函数可以工作,但我将它包含在参考中,因为它在ProcessSpike中)。

function [] = ProcessSpike(dataset,element,cluster)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
result = []
for a = 1:element
    for b = 1:cluster
        result = [result AvSpike(dataset, a, b)];
        mean = nanmean(result)
        r = [result]'
        r(end+1) = num2str(mean)
    end
end


function [result] = AvSpike(dataset,element,cluster)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
Trans1 = dataset.Trans1;
Before_Trans1 = Trans1-600;
Firing_Time1 = dataset(cluster).time(dataset(cluster).time>Before_Trans1(element)&dataset(cluster).time<Trans1(element));
ISI1 = diff(Firing_Time1);
result = numel(ISI1)/600
result(result == 0) = NaN
end

2 个答案:

答案 0 :(得分:0)

打印是由缺少结尾;的行引起的,编辑器应在这些行下面绘制一条橙色线(警告)。 关于不匹配的维度,您尝试将字符串(char数组)添加到现有数组(r(end+1) = num2str(mean))。如果该char数组的长度与r中其他元素的长度不匹配,则会导致此类错误。我建议不要在这里使用num2str(),只需按一个值而不是值的字符串表示。

答案 1 :(得分:0)

我已经对代码的修订版添加了注释,希望能让事情变得更清晰。

result = [] 
for a = 1:element
    for b = 1:cluster
        % Concatenate vertically (use ;) so no need to transpose later
        result = [result; AvSpike(dataset, a, b)];
        % Use a semi-colon at the end of line to supress outputs from command window
        % Changed variable name, don't call a variable the same as an in-built function
        mymean = nanmean(result); 
        % r = result'  % This line removed as no need since we concatenated vertically 
        % Again, using the semi-colon to supress output, not sure why num2str was used
        r(end+1) = mymean; 
    end
end
disp(r) % Deliberately output the result!