Как график из матлаба перенести в ворд
Есть следующий вопрос: можно ли экспортировать значения переменных и графики из Матлаба в Ворд? И если можно, то как это делается стандартными средствами?
Почитал про m-книги, однако, если я правильно понял, то m-книги позволяют лишь запускать функции матлаба из ворда, а это не совсем то, что нужно.
Спасибо.
импорт из matlab в MsWord
здравствуйте. есть ли возможность читать из matlab текстовые документы doc, созданные в micrasoft.
Экспорт из Matlab в Excel
Здравствуйте. Имеется файл .mat, состоящий из одной длинной (до 1 млн. значений) строки. Необходимо.
Графики в Matlab
Задание 2. На одном графике построить 3 кривые: соответствующую первому слагаемому (красная.
графики в Matlab
Здравствуйте! Подскажите пожалуйста, как построить график с двумя и более движущимися точками.
Если честно, то не совсем понятно задание. Вам нужно экспортировать данные в Ворд в каком виде? Как картинку, как таблицу или что-то ещё? Не понятно чем именно не устраивают м-книги.
Постараюсь уточнить вопрос. Запускаю скрипт в матлабе. Получаю результаты в виде значений набора переменных. Есть необходимость эти переменные экспортировать в определенные места документа ворд.
То же с графиками.
М-книги же делают немного другое: сам матлабовский скрипт запускается из ворда. В этом проблема.
Спасибо.
Что Вам мешает скопировать данные из командного окна Матлаб и вставить их в Ворд?
Не знаю поможет ли Вам, но посмотрите на оформление отчётов в Матлаб.
Спасибо.
Нужно найти как вопрос экспорта переменных из матлаба решается с помощью стандартных матлаб функций (не с помощью дополнительных графических надстроек)
Графики в matlab
Написал свой код , который выводит 3 графика , но параболу немного странно выводит , подскажите .
Графики в Matlab.
Помогите пожалуста с лабой. завтра сдавать, а сделать не получается. =( Был бы очень.
Графики в Matlab
>> f=0:0.1:pi;polar(f,-((5*cos(2*f))/cos(f)));grid . Error using ==> polar at 61 THETA and RHO.
Экспорт графики из отчета в word
Как сделать так чтобы картинка, (логотип фирмы), отображаемая в отчете, экспортировалась бы и в.
Экспорт графика из Matlab в Excel
Добрый день! Не нашел информации по вставке графика из матлаба в эксель. Например, имею.
exportgraphics( obj , filename ) saves the contents of the graphics object specified by obj to a file. The graphics object can be any type of axes, a figure, a standalone visualization, a tiled chart layout, or a container within the figure. The resulting graphic is tightly cropped to a thin margin surrounding your content.
exportgraphics( obj , filename , Name,Value ) specifies additional options for saving the file. For example, exportgraphics(gca,"myplot.jpg","Resolution",300) saves the contents of the current axes as a 300-DPI image file.
Examples
Export Axes as Image File
Create a line plot and get the current axes. Then save the contents of the axes as a JPEG file.
Specify Image Resolution
Display an image and get the current axes. Then save the contents of the axes as a 300-DPI JPEG file.
Export Figure
Display a plot with an annotation that extends beyond the bounds of the axes. Save the contents of the figure as a PDF file.
Export as PDF Containing Only Vector Graphics
Display a bar chart and get the current axes. Then save the contents of the axes as a PDF containing only vector graphics.
Export Multipage PDF
To create multipage PDFs, set the 'Append' name-value argument to true .
For example, create a line plot and save the contents of the axes to the file myplots.pdf .
Next, create a bar chart and save the contents of the axes as a second page in myplots.pdf .
Export Animated GIF
Plot a parabola with one marker. Change the location of the marker with every iteration of a for loop, and capture the changes as frames in an animated GIF.
Export Tiled Chart Layout
Display two plots in a tiled chart layout. Then save both plots as a PDF by passing the TiledChartLayout object to the exportgraphics function.
If you want to save just one of the plots in the layout, call the nexttile function with the axes return argument. Then pass the axes to the exportgraphics function.
Export Heatmap as PDF With Transparent Background
Display a heatmap chart. Then save the chart as a PDF containing only vector graphics with a transparent background.
Create App for Saving Plot
Create a program file called saveapp.m that displays a plot and a button for saving the axes content. In the callback function for the button, call the uiputfile function to prompt the user for a file name and location. Then call the exportgraphics function with the full path to the specified file.
Run the app by calling the saveapp function. When you click the Save Plot button in the app, a dialog box prompts you for a file name and location. Then the axes content is saved in the specified file. The area surrounding the axes, including the button, is not included in the file.
Input Arguments
obj — Graphics object
axes | figure | standalone visualization | tiled chart layout | .
Graphics object, specified as one of these objects:
Any type of axes: an Axes , PolarAxes , or GeographicAxes object.
A figure created with either the figure or uifigure function.
A standalone visualization such as a heatmap chart.
A tiled chart layout, which you create with the tiledlayout function.
Capture Area
exportgraphics captures the contents of the object you specify. It does not capture UI components such as buttons or sliders.
It also does not capture adjacent containers or child containers. For example, consider a figure containing a line plot with an adjacent panel containing a heatmap:
When you run the preceding code, myfigure.jpg contains the line plot, but not the heatmap. Similarly, mypanel.jpg contains the heatmap, but not the line plot.
filename — File name
character vector | string scalar
File name, specified as a character vector or a string scalar that includes the file extension. If filename does not include a full path, MATLAB ® saves the file in the current folder. You must have permission to write to the file.
The following table lists the supported file formats and the file extensions (which are not case sensitive).
Joint Photographic Experts Group (JPEG)
Portable Network Graphics (PNG)
Tagged Image File Format (TIFF)
Graphics Interchange Format (GIF)
Portable Document Format (PDF)
The PDF includes embeddable fonts when the ContentType is set to 'vector' .
Enhanced Metafile for Windows ® systems only (EMF)
Encapsulated PostScript ® (EPS)
Example: exportgraphics(gca,'myfile.jpg') saves the contents of the current axes to a JPEG file called myfile.jpg .
Name-Value Arguments
Specify optional pairs of arguments as Name1=Value1. NameN=ValueN , where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: exportgraphics(gca,'myplot.jpg','Resolution',300) saves the contents of the current axes to a 300-DPI image file.
ContentType — Type of content
'auto' (default) | 'vector' | 'image'
Type of content to store when saving as an EMF, EPS, or PDF file. Specify the value as one of these options:
'auto' — MATLAB controls whether the content is a vector graphic or an image.
'vector' — Stores the content as a vector graphic that can scale to any size. If you are saving a PDF file, embeddable fonts are included in the file.
'image' — Rasterizes the content into one or more images within the file.
Note
The 'vector' option is not supported for JPEG, TIFF, and PNG files.
If you specify the 'vector' option, some visualizations might contain stray lines or other artifacts.
Resolution — Resolution (DPI)
150 (default) | whole number
Resolution in dots per inch (DPI), specified as a whole number that is greater than or equal to 1 .
Specifying the resolution has no effect when the ContentType is 'vector' .
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
BackgroundColor — Background color
[1 1 1] (default) | 'current' | 'none' | RGB triplet | 'r' | 'g' | 'b' | .
Background color, specified as 'current' , 'none' , an RGB triplet, a hexadecimal color code, or a color name. The background color controls the color of the margin that surrounds the axes or chart.
A value of 'current' sets the background color to the parent container's color.
A value of 'none' sets the background color to transparent or white, depending on the file format and the value of ContentType :
Transparent — For files with ContentType='vector'
White — For image files, or when ContentType='image'
When ContentType='auto' , MATLAB sets the background color according to the heuristic it uses to determine the type content to save.
Alternatively, specify a custom color or a named color.
Custom Colors and Named Colors
RGB triplets and hexadecimal color codes are useful for specifying custom colors.
An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1] ; for example, [0.4 0.6 0.7] .
Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.
Есть ли функция которая будет вставлять графики в Word сама? Графиков очень много и вручную это делать очень долго.
не думаю, что в этом есть прелесть..
сохраните все картинки в jpg, в ворде в меню выберите вставить рисунок из файла и там выберете ВСЕ картники сразу. вот и все
немогу такую функцию найти.
Помогите отыскать, плиз, и ответьте на вопрос подробнее
amandra писал(а): не думаю, что в этом есть прелесть..
сохраните все картинки в jpg, в ворде в меню выберите вставить рисунок из файла и там выберете ВСЕ картники сразу. вот и все
когда программа выдает несколько десятков фигур с графиками, и нужны все, то прелесть очевидна.
особенно во время отладки программы..
Предлагаю, на мой взгляд, простой вариант автоматического формирования графических файлов, которые затем вручную вставите в Word. См. функцию print
Например
print 'Figure1' -dtiff -r300
function WriteToWordFromMatlab
% -------------------------------------------------------------------
% File: WriteToWordFromMatlab
% Descr: This is an example of how to control MS-Word from Matlab.
% With the subfunctions below it is simple to automatically
% let Matlab create reports in MS-Word.
% This example copies two Matlab figures into MS-Word, writes
% some text and inserts a table.
% Works with MS-Word 2003 at least.
% Created: 2005-11-22 Andreas Karlsson
% History:
% 051122 AK Modification of 'save2word' in Mathworks File Exchange
% 060204 AK Updated with WordSymbol, WordCreateTable and "Flying Start" section
% 060214 AK Pagenumber, font color and TOC added
% -------------------------------------------------------------------
WordFileName='TestDoc.doc';
CurDir=pwd;
FileSpec = fullfile(CurDir,WordFileName);
[ActXWord,WordHandle]=StartWord(FileSpec);
fprintf('Document will be saved in %s\n',FileSpec);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Section 1
%%create header in word
Style='Heading 1'; %NOTE! if you are NOT using an English version of MSWord you get
% an error here. For Swedish installations use 'Rubrik 1'.
TextString='Example of Report Generation from Matlab';
WordText(ActXWord,TextString,Style,[0,2]);%two enters after text
Style='Normal';
TextString='This is a simple example created by Andreas Karlsson, Sweden. ';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
TextString='Updated a sunny day, in February 2006, with -10 ';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
WordSymbol(ActXWord,176);%176 is the degree-symbol
TextString='C. ';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
TextString='The script will just insert a table and two figures into this document. ';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString='Last section is a short introduction for the interested users out there. ';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
TextString='My intention with this demo is to encourage you to let your powerful computer do the';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString=' "monkey-job" such as inserting figures into MS-Word and writing standard reports. ';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString='Hopefully these simple lines will help you getting more time for funny coding';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString=' and problem solving, increasing productivity in other words ';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString='by spending less time in Microsoft Office programs. ';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString='Happy coding!';
WordText(ActXWord,TextString,Style,[1,1]);%enter before and after text
ActXWord.Selection.InsertBreak; %pagebreak
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Section 3
style='Heading 1';
text='Table of Contents';
WordText(ActXWord,text,style,[1,1]);%enter before and after text
WordCreateTOC(ActXWord,1,3);
ActXWord.Selection.InsertBreak; %pagebreak
Style='Heading 2';
TextString='The Self-Explaining Table';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
%the obvious data
DataCell={'Test 1', num2str(0.3) ,'Pass';
'Test 2', num2str(1.8) ,'Fail'};
[NoRows,NoCols]=size(DataCell);
%create table with data from DataCell
WordCreateTable(ActXWord,NoRows,NoCols,DataCell,1);%enter before table
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Section 4
figure;plot([1:10]);title('Figure 1');xlabel('Time [s]');ylabel('Amplitude [A]')
%insert the figure
TextString='First figure';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
FigureIntoWord(ActXWord);
TextString='Second figure';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
figure;plot([1:19],[1:10,9:-1:1]);title('Figure 2');xlabel('Time [s]');ylabel('Amplitude [A]');legend('Signal 1',2)
FigureIntoWord(ActXWord);
ActXWord.Selection.InsertBreak; %pagebreak
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Section 5
Style='Heading 1';
TextString='Flying Start';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
Style='Normal';
TextString='Find out how to do new things in MS-Word by using the "Record Macro"-function ';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString='and look at the Visual Basic commands used.';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
TextString='In Matlab you find the available properties by using get(ActXWord), for top interface,';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString=' and further on with for example get(ActXWord.Selection).';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
TextString='Then find the methods usable from Matlab by using the invoke-function in Matlab ';
WordText(ActXWord,TextString,Style,[0,0]);%no enter
TextString='e.g. invoke(ActXWord.Selection). See the output of that call below. ';
WordText(ActXWord,TextString,Style,[0,1]);%enter after text
TextString='Set a breakpoint here and play around with these commands. ';
WordText(ActXWord,TextString,Style,[0,1],'wdColorRed');%red text and enter after text
%Make a long list of some of the methods available in MS-Word
Category='Selection'; % Category='ActiveDocument';
PrintMethods(ActXWord,Category)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%add pagenumbers (0=not on first page)
WordPageNumbers(ActXWord,'wdAlignPageNumberRight');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Last thing is to replace the Table of Contents so all headings are
%included.
%Selection.GoTo What:=wdGoToField, Which:=wdGoToPrevious, Count:=1, Name:= "TOC"
WordGoTo(ActXWord,7,3,1,'TOC',1);%%last 1 to delete the object
WordCreateTOC(ActXWord,1,3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CloseWord(ActXWord,WordHandle,FileSpec);
close all;
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function WordCreateTOC(actx_word_p,upper_heading_p,lower_heading_p)
% With ActiveDocument
% .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
% True, UseHeadingStyles:=True, UpperHeadingLevel:=1, _
% LowerHeadingLevel:=3, IncludePageNumbers:=True, AddedStyles:="", _
% UseHyperlinks:=True, HidePageNumbersInWeb:=True, UseOutlineLevels:= _
% True
% .TablesOfContents(1).TabLeader = wdTabLeaderDots
% .TablesOfContents.Format = wdIndexIndent
% End With
actx_word_p.ActiveDocument.TablesOfContents.Add(actx_word_p.Selection.Range,1.
upper_heading_p,lower_heading_p);
actx_word_p.Selection.TypeParagraph; %enter
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function WordText(actx_word_p,text_p,style_p,enters_p,color_p)
%VB Macro
%Selection.TypeText Text:="Test!"
%in Matlab
%set(word.Selection,'Text','test');
%this also works
%word.Selection.TypeText('This is a test');
if(enters_p(1))
actx_word_p.Selection.TypeParagraph; %enter
end
% actx_word_p.Selection.Style = style_p;
if(nargin == 5)%check to see if color_p is defined
actx_word_p.Selection.Font.Color=color_p;
end
actx_word_p.Selection.TypeText(text_p);
actx_word_p.Selection.Font.Color='wdColorAutomatic';%set back to default color
for k=1:enters_p(2)
actx_word_p.Selection.TypeParagraph; %enter
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function WordSymbol(actx_word_p,symbol_int_p)
% symbol_int_p holds an integer representing a symbol,
% the integer can be found in MSWord's insert->symbol window
% 176 = degree symbol
actx_word_p.Selection.InsertSymbol(symbol_int_p);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function WordCreateTable(actx_word_p,nr_rows_p,nr_cols_p,data_cell_p,enter_p)
%Add a table which auto fits cell's size to contents
if(enter_p(1))
actx_word_p.Selection.TypeParagraph; %enter
end
%create the table
%Add = handle Add(handle, handle, int32, int32, Variant(Optional))
actx_word_p.ActiveDocument.Tables.Add(actx_word_p.Selection.Range,nr_rows_p,nr_cols_p,1,1);
%Hard-coded optionals
%first 1 same as DefaultTableBehavior:=wdWord9TableBehavior
%last 1 same as AutoFitBehavior:= wdAutoFitContent
%write the data into the table
for r=1:nr_rows_p
for c=1:nr_cols_p
%write data into current cell
WordText(actx_word_p,data_cell_p{r,c},'Normal',[0,0]);
if(r*c==nr_rows_p*nr_cols_p)
%we are done, leave the table
actx_word_p.Selection.MoveDown;
else%move on to next cell
actx_word_p.Selection.MoveRight;
end
end
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function WordPageNumbers(actx_word_p,align_p)
%make sure the window isn't split
if (~strcmp(actx_word_p.ActiveWindow.View.SplitSpecial,'wdPaneNone'))
actx_word_p.Panes(2).Close;
end
%make sure we are in printview
if (strcmp(actx_word_p.ActiveWindow.ActivePane.View.Type,'wdNormalView') | .
strcmp(actx_word_p.ActiveWindow.ActivePane.View.Type,'wdOutlineView'))
actx_word_p.ActiveWindow.ActivePane.View.Type ='wdPrintView';
end
%view the headers-footers
actx_word_p.ActiveWindow.ActivePane.View.SeekView='wdSeekCurrentPageHeader';
if actx_word_p.Selection.HeaderFooter.IsHeader
actx_word_p.ActiveWindow.ActivePane.View.SeekView='wdSeekCurrentPageFooter';
else
actx_word_p.ActiveWindow.ActivePane.View.SeekView='wdSeekCurrentPageHeader';
end
%now add the pagenumbers 0->don't display any pagenumber on first page
actx_word_p.Selection.HeaderFooter.PageNumbers.Add(align_p,0);
actx_word_p.ActiveWindow.ActivePane.View.SeekView='wdSeekMainDocument';
return
style='Normal';
text=strcat('Methods called from Matlab as: ActXWord.',category_p,'.MethodName(xxx)');
WordText(actx_word_p,text,style,[0,0]);
text='Ignore the first parameter "handle". ';
WordText(actx_word_p,text,style,[1,3]);
MethodsStruct=eval(['invoke(actx_word_p.' category_p ')']);
MethodsCell=struct2cell(MethodsStruct);
NrOfFcns=length(MethodsCell);
for i=1:NrOfFcns
MethodString=MethodsCell{i};
WordText(actx_word_p,MethodString,style,[0,1]);
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FigureIntoWord(actx_word_p)
% Capture current figure/model into clipboard:
print -dmeta
% Find end of document and make it the insertion point:
end_of_doc = get(actx_word_p.activedocument.content,'end');
set(actx_word_p.application.selection,'Start',end_of_doc);
set(actx_word_p.application.selection,'End',end_of_doc);
% Paste the contents of the Clipboard:
%also works Paste(ActXWord.Selection)
invoke(actx_word_p.Selection,'Paste');
actx_word_p.Selection.TypeParagraph; %enter
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CloseWord(actx_word_p,word_handle_p,word_file_p)
if ~exist(word_file_p,'file')
% Save file as new:
invoke(word_handle_p,'SaveAs',word_file_p,1);
else
% Save existing file:
invoke(word_handle_p,'Save');
end
% Close the word window:
invoke(word_handle_p,'Close');
% Quit MS Word
invoke(actx_word_p,'Quit');
% Close Word and terminate ActiveX:
delete(actx_word_p);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Привет Великим Умам и Умницам.
Кто знает подскажите, хотя бы в каком направлении искать.
Задача следующая: программа анализа электр.сети почти написана (m-файл), осталось дописать скрипт для полного вывода результатов в Word. C текстовыми результатами проблем нет, а вот как сохранять графики в Worde не могу понять.
Поздравляю Всех с Новым 2008 Годом.
1. Спасибо, но сейчас уже начался 2009 год.
2. Если вручную сохранять рисунки, то проще всего на фигуре в меню выбрать запомнить, а в документе вставить.
С.П.Иглин
Oooops ошибочка, с Новым 2009г.
Спасибо, но все таки желательно чтобы отчет в Word формировался в полном и готовом виде.
Тогда m-book.
А как вы передаёте текст в word? Пишите сценарий на VBScript? Или просто копируете и вставляете вручную?
С.П.Иглин
Всем спасибо, на обменнике матлаб нашел то что надо.
Если кого то заинтересует, код здесь.
try,
inRow = figDimIn(1);
inCol = figDimIn(2);
catch,
inRow = 3;
inCol = 5;
end
if(~exist('figHandle', 'var')),
figHandle = gcf;
else,
if(isempty(figHandle)),
figHandle = gcf;
end
end
if(~exist('figCaption', 'var')),
figCaption = '';
else,
if(isempty(figCaption)),
figCaption = '';
end
end
try,
print -dmeta;
endOfDocument = get(wordActiveX_GLOBAL.activedocument.content,'end');
wordActiveX_GLOBAL.Application.Selection.Start = endOfDocument;
wordActiveX_GLOBAL.Application.Selection.End = endOfDocument;
% inf will force the last picture to be selected
resizeWordPicture(inf, [inRow, inCol]);
% [] is default for current location
addCaptionToWordFigure([], figCaption);
catch,
fprintf('%s - figure not copied to word correctly\n', mfilename);
Часто при исследовании какой-либо системы, требуется производить неоднократные опыты, а после этого анализ снятых данных.Поэтому в данной статье я решил поделиться опытом формирования отчетов проделанной работы в Microsoft Word. Итак, начнем.
Создание модели «simulink»
Модель simulink будет представлять собой генератор «белого шума» и осциллограф снимающий значения.
Чтобы создать новую модель нажимаем на верхней панели инструментов «Simulink».В итоге мы должны получить следующую модель. Сохраняем ее под именем «test.mdl»
Создание формы(GUI)
Cоздадим графический интерфейс нашей программы, для этого в matlabe существует утилита GUI(builder), ее можно найти нажав пуск в главном окне, и выбрав пункт Matlab->GUI(builder).
Интерфейс этой утилиты прост, поэтому трудностей при создания формы не возникнет.
Поместим на форму две кнопки(start и save) и axes(сюда мы будем рисовать график). В итоге мы получим следующую форму.
Также добавим обработчики событий на кнопки.
Для кнопки start:
function Start_Callback(hObject, eventdata, handles)
open_system('test');//открытие симулинк модели
open_system('test/Scope');//открытие осциллографа
set(handles.figure1, 'UserData',gcf);//запоминаем десриптор окна осциллографа
sim('test');//запуск модели симулик
axes(handles.axes1);
x = -pi:pi/10:pi;
plot(x);//рисуем простой график в axes
Для кнопки stop:
set(hObject,'Enable','off');//делаем не активной кнопку save
reporter(hObject, eventdata, handles);//вызываем функцию снятия скриншота формы
reporter_dop(hObject, eventdata, handles);//вызываем функцию снятия скриншота осциллографа
docrep;//сохраняем вcе word
Сохраняем форму под именем «testForm».
Коды функций reporter,reporter_dop,docrep
Каждую функцию следует поместить в отдельный файл с именем функции.
Код функции reporter:
function reporter(hObject, eventdata, handles)
dir = 'c:\';//директория, где будут храниться код.
n = 1;
if ~isempty(dir),
pngFile = strcat(dir,'data-',num2str(n),'.jpg');
scrshot = getframe(gcf);//снимаем скриншот,gcf дескриптор окна формы
imwrite(scrshot.cdata,pngFile,'png','Transparency',get(gcf,'color'));//создаем файл картинки
end
funkname = 'скрин';
filename=sprintf('%s','data-',num2str(n));
pathname=dir;
//записываем данные в файл
if filename~=0
[fid,message] = fopen(strcat(pathname,filename,'.txt'),'w');
if fid~=-1
fprintf(fid,funkname);
fprintf(fid,'\n[image]\n');
fclose(fid);
end
end
Функция reporter_dop имеет похожий код только вместо дескриптора формы берем дескриптор осциллографа.
Код сохранения в word:
dir = 'c:\';
n = 2;
list = [];
if exist(dir,'dir'),
dotFile = strrep(mfilename('fullpath'),mfilename,'report.doc');//Шаблон файла word
docFile = strcat(dir,'отчет.doc');
Word = actxserver('Word.Application'); //Создаем COM Сервер Word записываем раннее подготовленные файлы
%set(word,'Visible',1);
Doc = Word.Documents.Open(dotFile);
Doc.SaveAs(docFile,1);
Selection = Word.Selection;
Selection.Start = Doc.Content.End;
Selection.End = Doc.Content.End;
FLI = Selection.ParagraphFormat.FirstLineIndent;
for i = 1:n,
pngFile = strcat(dir,'data-',num2str(i),'.jpg');
txtFile = strcat(dir,'data-',num2str(i),'.txt');
if exist(pngFile) & exist(txtFile),
fid = fopen(txtFile);
while 1,
tline = fgetl(fid);
if ~ischar(tline), break; end;
if strncmp(tline,'[image]',7),
Selection.ParagraphFormat.Alignment = 1;
Selection.ParagraphFormat.FirstLineIndent = 0;
Selection.InlineShapes.AddPicture(pngFile);
Selection.TypeParagraph;
Selection.TypeText(strrep(tline,'[image]',''));
Selection.TypeParagraph;
Selection.ParagraphFormat.Alignment = 0;
Selection.ParagraphFormat.FirstLineIndent = FLI;
elseif strncmp(tline,'[i]',3),
Selection.Font.Italic = 1;
Selection.TypeText(strrep(tline,'[i]',''));
Selection.Font.Italic = 0;
else
Selection.TypeText(tline);
end;
Selection.TypeParagraph;
end
fclose(fid);
end;
end;
Doc.Close;
Word.Quit;
disp(strcat('Создан файл отчета',dir));
else disp('Ошибка при создании файла отчета. ');
end;
Запуск программы
Чтобы запустить нашу программу, после запуска Matlab, необходимо добавить путь к директории с нашими файлами командой: addpath путь к директории.
В итоге после работы программы мы получим файл отчет.doc.
Читайте также: