0

A few days ago I posted this question and got the following splendid solution:

fid = fopen('C:\Testes_veloc\test.txt', 'Wt');
fmt = sprintf('%s;%d;%%d;%d;%d;%%d;%%d;%%d;%%.4f \\n',str1,num1,0,2)
[a,b,c,d] = ndgrid(vect2,vect1,day,1:15);
out = sprintf(fmt, [d(:), c(:), b(:), a(:), reshape(permute(MD,[2,1,3,4]),[],1)]'); 
fprintf(fid, '%s', out);

The variables str1, num1, day, vect1, vect2 and MD are inputs of this function:

  • str1 is a string 1x1
  • num1 is an integer 1x1
  • day is a vector 10x1
  • vect1 is a vector 7x1
  • vect2 is a vector 180x1
  • MD is a 4D matrix (7x180x10x15)

The objective was to have a text file as follows:

result.txt:
RED;12;7;0;2;1;4;7;0.0140
RED;12;7;0;2;2;9;7;0.1484
RED;12;7;0;2;3;7;4;0.1787
RED;12;7;0;2;4;2;6;0.7891
RED;12;7;0;2;5;9;6;0.1160
RED;12;7;0;2;6;9;1;0.9893

However, str1 is not a 1x1 string; it's a vector of names (189000x1), that has the length of the text that I desire. In other words, instead of only 'RED', I have many different others strings. Is it possible to adjust this vectorized loop to this situation?

I tried this (add the str1(:) to the concatenation part), but unsuccessfully:

fmt = sprintf('%%s;%s;%d;%%d;%d;%d;%%d;%%d;%%d;%%.4f \\n',str1,num1,0,2)
out = sprintf(fmt, [str1 (:), d(:), c(:), b(:), a(:), reshape(permute(MD,[2,1,3,4]),[],1)]'); 

For example, str(1,:) = 'RED'; str(2,:) = 'FHAW'; str(3,:) = 'KI81'; a cell like this. It fails to concatenate the string to the numbers. Does anyone have solution?

Thanks in advance.

4

1 回答 1

1

sprintf(如 fprintf)使用参数按照提供的顺序填充格式字段。如果您提供的参数多于格式要求的参数,这些函数会使用附加函数重复格式:

sprintf('%s %i\n', 'a', 1, 'b', 2, 'c', 3)

% returns

ans =

a 1
b 2
c 3

使用 Matlab 的单元解开技术,您可以先准备参数,然后将它们传递给 sprintf:

tmp = {'a', 1, 'b', 2, 'c', 3};
sprintf('%s %i\n', tmp{:})

您可以通过连接元胞数组来获得更好的体验:

tmp1 = {'a','b','c'};
tmp2 = [1 2 3];
tmp = [tmp1' num2cell(tmp2')]'
sprintf('%s %i\n', tmp{:})

% Returns

tmp = 

    'a'    'b'    'c'
    [1]    [2]    [3]


ans =

a 1
b 2
c 3

请注意,tmp的布局是格式中布局的转置。这是因为 Matlab 以行优先顺序读取数据,因此它将向下行进,然后是列,以获取 sprintf 的参数。

因此,在您的场景中,您需要使用您的参数创建一个大型元胞数组,然后将其传递给 sprintf。

fid = fopen('C:\Testes_veloc\test.txt', 'Wt');
fmt = sprintf('%%s;%d;%%d;%d;%d;%%d;%%d;%%d;%%.4f \\n',num1,0,2)
[a,b,c,d] = ndgrid(vect2,vect1,day,1:15);
tmp = [str(:) num2cell([d(:) c(:) b(:) a(:) reshape(permute(MD,[2,1,3,4]),[],1)]'])]';
fprintf(fid, fmt, tmp{:});
fclose(fid);
于 2013-08-30T22:26:34.707 回答