if I have data from a mat file say
3 7 2005 30 %1st 3 columns are day month year print loss
1 4 2005 35
1 5 2005 24
2 6 2005 25
.....
% I have code that gets the data I want say index= [1;2;4] and values=[10;20;30] Id like to print the date and value corresponding
%the index and value
How would I use fprintf or disp to get something like
'One of the 3 big losses occurs on the 3rd of July 2005 with a loss of 30' %Is it possible to write it as something like
'One of the 3 big losses occurs on the data(i,index(1)) of data(i,index(2)) data(i,index(3)) with a loss of values(3)'

 採用された回答

Star Strider
Star Strider 2019 年 10 月 13 日

1 投票

Try this:
M = [3 7 2005 30
1 4 2005 35
1 5 2005 24
2 6 2005 25];
MDate = datetime(M(:,3),M(:,2),M(:,1));
% MDates = cellstr(MDate); % Optional
for k = 1:size(M,1)
fprintf('One of the 3 big losses occurs on %s with a loss of %d\n', MDate(k), M(k,4))
end
The loop is necessary, since fprintf has different variable types (datetime and double) in its arguments.

4 件のコメント

jacob Mitch
jacob Mitch 2019 年 10 月 13 日
編集済み: jacob Mitch 2019 年 10 月 13 日
Hi there thank you for your help as it helping me understand. Is it possible to adjust this line because I have
index=[1;2;4]
value =[30;35;25]
%Is it possible adjust it to print based on what the above says,
%as the data is changing say something like for
'One of the 3 big losses occurs on %s with a loss of %d\n', MDate(index(1)), value(1)
'One of the 3 big losses occurs on %s with a loss of %d/n', Mdate(index(2)), value(2)
But it just prints
ans =
One of the 3 big losses occurs on %s with a loss of %d\n
ans =
datetime
3-Jul-2005
ans =
30
I really appreciate your help. Thank you
Star Strider
Star Strider 2019 年 10 月 13 日
My pleasure.
So long as ‘index’ are integers greater than 0 and address existing rows in ‘M’, this will work:
index = [1;2;4];
value = [30;35;25];
for k = 1:numel(index)
fprintf('One of the 3 big losses occurs on %s with a loss of %d\n', MDate(index(k)), value(k))
end
(I did not re-post ‘M’ and ‘MDate’ here. I assume they already exist in your workspace.)
jacob Mitch
jacob Mitch 2019 年 10 月 13 日
This is absolutely perfect, thank you so much
Star Strider
Star Strider 2019 年 10 月 13 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by