【问题标题】:for loop prints the same thing in each iteration, should only print it oncefor循环在每次迭代中打印相同的东西,应该只打印一次
【发布时间】:2017-07-06 21:10:17
【问题描述】:

我的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

【问题讨论】:

  • 能否提供minimal reproducible example,即定义所有输入变量
  • 你想在你的 for 循环中打印什么?
  • 我想为给定集群打印 17 个不同元素的平均触发率列表。所以它应该在 r 上,意思如下,但我得到了 17 次相同的东西。
  • result = NaN mean = 1.7186 r = NaN NaN NaN NaN 0.0050 NaN NaN 2.3067 NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.1300 NaN NaN 0.4967 0.0350 NaN 10.8767 NaN(由于字符空间有限而缩写)
  • 您可以对您的问题进行编辑,而不是在 cmets 中使用缩写和未格式化的代码!

标签: matlab for-loop


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我已将 cmets 添加到您的代码的修订版本中,希望能让事情变得更清晰。

    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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多