2015-10-06 2 views
1

Я пытаюсь построить график тысяч точек данных, содержащих x, y, z, t. Данные в текстовый файл и выглядит следующим образом:Matlab 4dplot (x, y, z, t)

  • [х, у, г, время]
  • [50,9160, 12,2937, -44,9963, 0,0]
  • [50,9160, 12,2937, - 44,9963, 0,8]
  • [50,9160, 12,2937, -44,9963, 1.8]
  • [50,9160, 12,2937, -44,9963, 2.8]
  • [50,9160, 12,2937, -44,9963, 3,8]
  • [50,9160, 12,2937 , -44,9963, 4,9]
  • [50,9160, 12,2937, -44,9963, 8.8]
  • [50,9160, 12,2937, -44,9963, 11.1]
  • [50,9160, 12,2937, -44,9963, 11.7]
  • [50,9160, 12,2937, -44,9963, 12,8 ]
  • [50,8989, 12,3248, -45,0376, 13.7]
  • [50,8989, 12,3248, -45,0376, 14.9]
  • [50,8989, 12,3248, -45,0376, 15.7]
  • [50,8989, 12,3248, -45,0376 , 17.2]
  • [50. 8989, 12,3248, -45,0376, 17,7]
  • и т.д. (более тысячи точек данных)

Я имею в виду вдоль линии открытия текстового файла, создавая цикл, который будет захватывать х, у, z, t и использовать разброс 3 для построения графика. Если бы кто-нибудь мог заставить меня начать с того, как должен выглядеть код MATLAB, это было бы здорово.

+1

Может не Документы Matlab, чтобы вы начали? Попробуйте что-нибудь и отправьте код, прежде чем спрашивать: http://www.mathworks.com/help/matlab/ref/csvread.html и http://www.mathworks.com/help/matlab/ref/scatter3.html для стартеры – Dan

+0

Как говорит Дэн, вы должны прочитать эти документы и попробовать некоторые из этих примеров. Самая большая проблема, которую я вижу, - как сгенерировать время. Для этой проблемы я считаю, что лучше всего использовать кодировку времени, но с уверенностью сказать трудно, прежде чем увидеть результаты. Кроме того, время, когда цветовой код является бит-счетчиком, интуитивно понятен. Однако это поможет дать направление линии (поскольку данные отбираются) – patrik

+1

Эй. Посмотрите на различные возможности построения 4D: https: //stackoverflow.com/questions/27659632/reconstructing-three-dimensions-image-matlab/27660039#27660039 https://stackoverflow.com/questions/29229988/visualize-a - трехмерная матрица-подобная-кубическая решетка-использование-матлаб/29233108 # 29233108 или https://stackoverflow.com/questions/31828064/constructing-voxels-of-a-3d-cube-in-matlab/31829681 # 31829681 –

ответ

1

Я действительно не понимаю, как вы хотите построить в 4D, но я предполагаю, что вы хотите построить в 3D, а затем динамически изменять сюжет с течением времени.

Но в любом случае, о файлах:

Во-первых, чтение текста действительно просто.

  1. Вам просто нужно создать переменную, т.е. file_text_rd, а затем использовать эту переменную, чтобы открыть файл:

    file_text_rd = fopen('data.txt','r');

    Первый параметр является именем файла .txt (Обратите внимание, что вы необходимо установить каталог в папку, где находится файл .txt). Второй параметр указывает, что вы хотите прочитать из текстового файла.

  2. Затем вы можете прочитать из файла и поместить данные в переменные с различной функцией (в зависимости от того, что вам подходит). Например,

    var=fgetl(file_text_rd);

    поставит первую строку содержимого файла в переменную.

    var=fscanf(file_text_rd,%c);

    поместит все содержимое файла .txt в переменной и т.д. Другие функции чтения являются fread и fgets. Таким образом, в зависимости от функции вы можете использовать некоторые функции циклирования, чтобы заполнить ваш контент var.

  3. Когда вы закончите с чтением файла, необходимо закрыть файл с:

    fclose(file_text_rd), clear file_text_rd;

Следующая часть может быть немного сложнее. Это часть, в которой вы конвертируете символы, которые вы прочитали в целые числа. Я написал немного кода для вас, чтобы проиллюстрировать один из способов сделать это. В этом решении я использовал функцию fscanf.

%Open file for reading 
file_text_rd=fopen('data.txt','r'); 
%Read the content (%c means you are reading characters) 
var=fscanf(file_text_rd,'%c'); 
%Converse the characters to double. Have in mind the ascii values of the 
%chars, so you can get the actual number value of the numbers in the string 
%by subtracting the 48 of the original value, since the zero in ascii is 
%numbered as 48 (in decimal system). 
conv_var=double(var)-48; 
%Define the initial value of your variable (all zeros) 
final_var=zeros(1,4); 
%Row counter 
count_r=1; 
%Column counter 
count_c=1; 
%Divider 
times=10; 
%Dot flag 
dot=0; 
%Negative sign flag 
negative_sign=0; 
%This for loop is for testing every single character from the first to the 
%last 
for i=1:size(conv_var,2)-1  
    %This if condition is for: 
    %1. Checking if the character is a number between 0 and 9 
    %2. Checking if the character is a dot 
    %3. Checking if the character is a minus sign 
    %4. Checking if the character is a comma 
    %All other characters are not of interest. 
    if (conv_var(i)>=0 && conv_var(i) <=9) || conv_var(i) == -2 || conv_var(i) == -3 || conv_var(i) == -4 

     %If it's not a comma (that means we are still on the last number we 
     %were working on) we go in this section 
     if conv_var(i)~= -4 
      %If it's not a minus sign we go in this section 
      if conv_var(i) ~= -3 
       %If the dot flag hasn't been set to 1 yet (no dot in the 
       %string has yet been found) we don't enter this section 
       if dot==1 
        %If the flag HAS been set, then the number just found 
        %on the sequence is divided by 10 and then added to the 
        %old versison, since if we are reading the number 
        %'50.9160', the 9 has to be divided by 10 and then 
        %added to 50 
        final_var(count_r,count_c)=final_var(count_r,count_c)+conv_var(i)/times; 
        %The divider now rizes because the next found number 
        %would be 10 times smaller than the one found just now. 
        %For example, in '50.9160', 1 is 10 times less than 9 
        times=times*10; 
       else 
        %This condition is needed so we don't add the ascii 
        %number equivalent to the dot to the number we are 
        %working on. 
        if conv_var(i)~=-2 
         %We multiply the old version of the number we are 
         %working on, since if we are reading the number 
         %'50.9160', first we will read 5, then we will read 0, 
         %so we will need to multiply 5 by 10 and then add the 0 
         %and so on... 
         final_var(count_r,count_c)=final_var(count_r,count_c)*10+conv_var(i); 
        else 
         %If the character found IS the dot, then we just 
         %set the flag 
         dot=1; 
        end 
       end 
      else 
       %If the character found IS the negative_sign, then we set 
       %the flag for the negative_sign, so we can multiply the 
       %number we are working on atm with -1. 
       negative_sign=1; 
      end    
     else 
      %We get in this section if we found a comma character (or the 
      %ascii equvalent of the comma sign, more accurately) 
      if negative_sign==1 
       %This is the part where we multiply the number by -1 if 
       %we've found a minus sign before we found the comma 
       final_var(count_r,count_c)=-final_var(count_r,count_c); 
      end 

      %Here we add 1 to the column counter, since we are ready to 
      %work with the next number 
      count_c=count_c+1; 

      %We reset all the flags and the divider 
      dot=0; 
      times=10; 
      negative_sign=0; 
     end 

    end 

    %The number -38 in ascii is the equivalent of NL, or the end of the 
    %line sign (which we can't see), which actually means there was an "Enter" pressed at this point 
    if conv_var(i)==-38 
     %We set the column counter to one since, we will work now with the 
     %first number of the next four parameters 
     count_c=1; 

     %We increment the row counter so we can start saving the new values 
     %in the second row of our matrix 
     count_r=count_r+1; 

     %We set the next row initially to be all-zeros 
     final_var(count_r,:)=zeros(1,4); 

     %We reset the flags 
     dot=0; 
     times=10; 
     negative_sign=0; 
    end 
end 

%We close the file, since our work is done (you can put this line after the 
%fscanf if you like) 
fclose(file_text_rd), clear file_text_rd; 

Я считаю, что у вас есть некоторое представление о том, как построить свои данные 4D, несмотря на то, что я не могу поймать эту часть вверх.

Я надеюсь, что я помог, Боян

+0

Благодарим за помощь! У меня есть еще один вопрос. По моим данным у меня есть отрицательный знак перед скобками. . Пример: - [50,9160, 12,2937, -44,9963, 0,0] - [50,9160, 12,2937, -44,9963, 0,8]. Не могли бы вы изменить свой код, чтобы отрицательный результат в начале не учитывался? – Sagistic

Смежные вопросы