2016-07-27 83 views
0

我有下面的工作代码,它显示每小时后的参数计数。代码使用两个函数。基本上我的代码确实MATLAB存储循环到表格的值

  • 用户运行test_main(小时,总参数)
  • test_main产生随机数
  • test_main发送号码test_sub
  • test_sub的数量响应

test_main功能

function[] = test_main(x, pc) 

for i = 1:x %loop for time 
    fprintf('\n Time is %d hour after count start . \n', i); 

    for t = 1:pc 
     fprintf('\nPARAMETER at test main %d ', t); 

     w=rand; %random error generator. 
     if w<0.5 
      status=1; 
     else 
      status=99; 
     end 

    % fprintf('\n Time is %d hour after count start . \n', i); 

    test_sub(status); 
    end 
end 
end 

test_sub功能

function[a] = test_sub(z) 

%fprintf('\nPARAMETER inside test sub %d ', count) 
fprintf('\n Value is %d \n', z); 

    if (z==1) %if input equal to 0 
    j=1; %store temporary value to j 
    a=j; 
    disp('new value is 1') 

    elseif (z==99) 
    j=1; 
    a=j; 
    disp('new value is 100') 
else 
disp('unidentified error') 
end 
end 

我注意到,我还没有从test_sub到test_main发送值返回。我不知道如何将每个循环后的值记录到表格中。我需要的表如下所示:根据在test_main功能用户插入值

  Parameter 1 Parameter 2 ..... parameter N 
Time 1  1    100 
Time 2  100    1 
.... 
Time N 

能参数和时间展开?

回答

0

好的我不太确定该功能是干什么的,但创建你想要的表可能就足够了。我假设x和pc只是数字,你没有每个参数的名称。我会先创建一个单元阵列,然后将其转变成一个表:

function [output] = test_main(x, pc) %this functions output would be the table you want 
    cell_array=cell(x,pc+1); %creating a cellarray first 
    names=cell(1,pc+1); 
    names{1,1}='Time'; 
    for i = 1:x %loop for time 
     fprintf('\n Time is %d hour after count start . \n', i); 
     cell_array{i,1}=i; 

     for t = 1:pc 
      fprintf('\nPARAMETER at test main %d ', t); 

      w=rand; %random error generator. 
      if w<0.5 
       status=1; 
      else 
       status=99; 
      end 

     % fprintf('\n Time is %d hour after count start . \n', i); 

     cell_array{i,t+1}=test_sub(status); %writing in row i at column t the value of test_sub 
     names{1,t+1}=['Parameter_' num2str(t)]; 
     end 
    end 

    output=cell2table(cell_array,'VariableNames',names); %transforming it into a table 

end 
在你的,如果“A = 1”我觉得第二个应该是100的输出如下的两种情况下写test_sub

就像你的例子,但参数名不会变成'参数X'。你可以在cell2table中做到这一点,如果你想

+0

我该如何显示cell_array旁边的时间? –

+0

我编辑我的答案 – Finn

+0

当我更改cell_array,时间列也改变。它可以像time_array cell_array1 cell_array2? –